walk script fixing needed pls (easy for you i guess ;) )

Hey guys. I´ve just made my character move relative to my camera in two lines after i tried doing it in more than 10 :wink:

function Update () 
{
	this.transform.position +=Camera.mainCamera.transform.forward*Input.GetAxis("Vertical")*movementspeed;
	this.transform.position +=Camera.mainCamera.transform.right*Input.GetAxis("Horizontal")*movementspeed;
}

Now i want this character to move on a plane and not trough it. Actually if i press “w” it will fly through the plane it is standing on but i want to have it moving on in realtive to the camera? Do you know how to do it? I would be very happy :slight_smile:

Instead of

Camera.mainCamera.transform.forward

use a cross product like this

Vector3.Cross(Camera.mainCamera.transform.right, Vector3.Up)

You’ll probably need to multiply it by -1 too.

Best regards,
Peter.

What you’re going to want to do is derive forward and right directions that are relative to the camera but parallel to your plane of movement. Use the cross product between your camera’s right direction and a vector that’s perpendicular to your movement plane (Vector3(0.0f, 1.0f, 0.0f) for the XZ plane) like so to get your forward movement direction:

var forwardDirection = Vector3.Cross(Camera.transform.right,PlaneNormal);

Then do the same with the PlaneNormal and forwardDirection like so to get your right direction:

var rightDirection = Vector3.Cross(PlaneNormal, forwardDirection);

Now you can scale them with your Input axes values and add them together to get your actual movement direction, normalizing the vector if its length is greater than one so that you can then scale it according to your movement speed:

var direction = (forwardDirection * vertical) + (rightDirection * horizontal);
if(direction.sqrMagnitude > 1.0f)
{
    direction.Normalize();
}
var velocity = direction * Speed;

And finally translate your character by the velocity scaled by deltaTime:

transform.position += velocity * Time.deltaTime;

That’ll give you smooth movement relative to the camera and parallel to a movement plane.

Thank you very much i will try it soon :slight_smile: