- Home /
Player movement based on camera?
Hey guys, I'm having quite some problems with the player movement script.
I want to make the character movement based on the camera: for example, when I press W, the character will move and turn to the direction where the camera is facing.
Here's what I have now:
public float speed = 6f; // The speed that the player will move at.
public float rotateSpeed = 2f;
Vector3 movement; // The vector to store the direction of the player's movement.
Animator anim; // Reference to the animator component.
Rigidbody playerRigidbody; // Reference to the player's rigidbody.
int floorMask; // A layer mask so that a ray can be cast just at gameobjects on the floor layer.
float camRayLength = 100f; // The length of the ray from the camera into the scene.
Vector3 rotationY;
void Awake ()
{
// Create a layer mask for the floor layer.
floorMask = LayerMask.GetMask ("Floor");
// Set up references.
anim = GetComponent <Animator> ();
playerRigidbody = GetComponent <Rigidbody> ();
}
void FixedUpdate ()
{
// Store the input axes.
float h = Input.GetAxisRaw ("Horizontal");
float v = Input.GetAxisRaw ("Vertical");
// Move the player around the scene.
Move (-h, -v);
// Turn the player to face the mouse cursor.
Turning (h, v);
// Animate the player.
Animating (h, v);
}
void Move (float h, float v)
{
// Set the movement vector based on the axis input.
movement.Set (h, 0f, v);
// Normalise the movement vector and make it proportional to the speed per second.
movement = movement.normalized * speed * Time.deltaTime;
// Move the player to it's current position plus the movement.
playerRigidbody.MovePosition (transform.position + movement);
}
void Turning(float y, float x)
{
if (y != 0) {
rotationY.Set (0f, y, 0f);
rotationY = rotationY.normalized * (5 * rotateSpeed);
Quaternion deltaRotation = Quaternion.Euler (rotationY);
playerRigidbody.MoveRotation (deltaRotation);
}
}
Answer by AlwaysSunny · Apr 20, 2015 at 03:54 AM
This is the function I use to achieve this:
http://hastebin.com/irerafexut.avrasm
It assumes the camera might optionally orbit around the player, but not tilt (no Zed rotation). Also that the world "up" axis is Y, and you want your input returned on the XZ plane.
Pass your input vector in this format (Vector3(horizontal, 0, vertical)) to the "input" argument and your camera's transform to the "camera" argument. The function translates a world-space input vector into a camera-relative input vector.