Custom ship gravity rotation

Hi, I am trying to create several different gravity types for different objects. I am trying to create a gravity towards a ship (which is similar to planar), however I need to rotate the gravity axis as the ship turns and rotates.

on the ship is a script which makes the player child of the ship (via collider trigger) and sets gravity type in the player movement script. this is my movement script on the player:

using UnityEngine;
using System.Collections;

public class movement : MonoBehaviour {

	public float speed = 20f;
	public float jumpSpeed = 8f;
	public float gravity = 20f;
	public int gravity_type = 0;
	public GameObject sphere;
	private Vector3 moveDirection = Vector3.zero;
	
	void Update() 
	{
		CharacterController controller = GetComponent<CharacterController>();
		if (controller.isGrounded) 
		{
			moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection = moveDirection * speed;
			
			if (Input.GetButton ("Jump"))
			{
				moveDirection.y = jumpSpeed;
			}
		}
		
		switch (gravity_type)
		{
		case 1: // planar
			moveDirection.y = moveDirection.y - gravity * Time.deltaTime;
			break;
		case 2: // ship - doesnt work so far
			moveDirection.y = moveDirection.y - gravity * Time.deltaTime;
			moveDirection = Quaternion.Euler(0,0,gameObject.transform.parent.gameObject.transform.eulerAngles.y) * moveDirection;
			break;
		case 3: // sphere - doesnt work so far
			
			break;
		}
		
		// Move the controller
		controller.Move(moveDirection * Time.deltaTime);
	}
}

I’ve tried swapping the axis and it always messess up the walking directions. what am I doing wrong?

Gravity direction can just be determined by -ship.up for some ship Transform variable (thus it’ll be opposite to your ship’s up direction) and then you can get the magnitude of gravity by multiplying that by some gravityMagnitude float.

I’d write a function to get the ship’s gravity, for simplicity’s sake:

//somewhere inside your class...

public float gravityMagnitude = 9.81f;
public Transform ship;

//other class stuff here...

public Vector3 GetShipGravity() {
    return - ship.up * gravityMagnitude;
}

Just an FYI, you’ll also run into issues making a CharacterController rotate to the right direction. It’s made with the Y-axis as up by default… I think you can make a workaround by rotating the parent of the CharacterController’s Transform instead of rotating the CharacterController’s Transform directly?