- Home /
3D Top down movement. Move towards the mouse position.
Hello, im making a 3d top down game, and now my movement script make the player look at the mouse position in the map by a rayCast, and move around with the getAxis("Horizontal") and getAxis("Vertical"). Basically my problem its when i press W the player mover vertically, and i want him to move in the direction he is looking. Hope someone understand my question. Thanks.
void MovementTopDown()
{
{
moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = moveInput * moveSpeed;
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayLenght;
if (groundPlane.Raycast(cameraRay, out rayLenght))
{
Vector3 pointToLook = cameraRay.GetPoint(rayLenght);
Debug.DrawLine(cameraRay.origin, pointToLook, Color.red);
transform.LookAt(pointToLook);
}
}
}
void FixedUpdate()
{
rb.velocity = moveVelocity;
}
Answer by FortisVenaliter · Oct 05, 2017 at 06:57 PM
Okay, two things:
You should never set the Rigidbody.velocity variable. You're basically overriding the physics system, so when doing this you shouldn't use a Rigidbody at all. Remove it.
Your basic problem is that you need to convert your velocity from local space (forward is the entity's forward) to world space (forward is Z+ axis). To do this, you can use the Transform.TransformVector() function, then use that as the actual velocity.
what does this function? what vector should a put Transform.TransformVector(HERE) ?
That function will convert your velocity from local to world.
So, the parameter will be the velocity in local space (the one you're already calculating).
The output return value will be the velocity in world space (which you'll use to actually move your object).