I'm working on Mario Galaxy style walking and physics.
This code will attract the player (capsule with controller) towards the centre of the scene (0,0,0) and also rotate them so that they orient the right way up. It also stops the player from falling when they hit the planets surface. For my game I don't need to calculate rotations based upon the normal of the ground like they do in Mario. Just rotate towards a point.
This all works. However, now I need to rotate the player with the input controls. But I can't because the planet orientation code over rides this meaning that the player will not turn around when I press the keys!! How can I solve this???
Here is all my code so far:
/// This script moves the character controller forward
/// and sideways based on the arrow keys.
/// It also jumps when pressing space.
/// Make sure to attach a character controller to the same game object.
/// It is recommended that you make only one call to Move or SimpleMove per frame.
var speed = 6.0;
var rotateSpeed = 3.0;
var faux = Vector3.zero; //gravity value
private var moveDirection = Vector3.zero;
private var targetPos = Vector3.zero;
function FixedUpdate()
{
// Obtain Controller
var controller : CharacterController = GetComponent(CharacterController);
// Apply Gravity and Check to see if we have landed on planet (if so stop gravity)
var targetDir = transform.TransformDirection (-Vector3.up);
Debug.Log (targetDir);
if (!Physics.Raycast (transform.position, targetDir, 1.2))
{
print ("No Collision.");
//Debug.Log ("No collision found.");
faux += (transform.position - Vector3.zero).normalized * -2 * Time.deltaTime; //apply gravity
controller.Move(faux);
}
else
{
faux = Vector3.zero; // reset gravity
}
//Rotate Player towards centre of planet
transform.rotation = Quaternion.FromToRotation (Vector3.up, (transform.position - Vector3.zero).normalized);
//Apply movement from keys
moveDirection = Vector3(0 ,0 , Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
// Apply rotation from keys. DOESNT WORK!!
transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
var planet : Transform;
function FixedUpdate() {
// could be optimized
var direction = (planet.position - transform.position).normalized;
rigidbody.AddForce(
Physics.gravity.magnitude * direction, // pull towards planet center
transform.position - transform.up, // pull from feet to orient character
ForceMode.Acceleration // gravity is pure acceleration
);
}