- Home /
Make player move in local direction he is turned.
Hi, I am making a first person shooter, but i am having a little problem: My Character turns with my camera but when i start moving it still walks to the Space.World directions not to the local directions. how can i fix this?
This is my movement script:
void Start () { anim = GetComponent(); Rbody = GetComponent(); run = false; Cursor.lockState = CursorLockMode.Locked; }
// Update is called once per frame
void Update ()
{
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
Physics.gravity = new Vector3(0f, -Gravity * Time.fixedDeltaTime, 0f);
if (Input.GetKeyDown("1"))
{
anim.Play("Run", -1,0f);
}
if (Input.GetKey(KeyCode.LeftShift)&& inputV > 0.1)
{
currentrunspeed = 150f;
run = true;
}
else
{
run = false;
currentrunspeed = 80f;
}
inputH = Input.GetAxis("Horizontal");
inputV = Input.GetAxis("Vertical");
anim.SetFloat("InputH", inputH);
anim.SetFloat("InputV", inputV);
anim.SetBool("Run",run);
float moveX = inputH * 50f * Time.deltaTime;
float moveZ = inputV * currentrunspeed * Time.deltaTime;
Rbody.velocity = new Vector3(moveX,Rbody.velocity.y, moveZ);
if (Input.GetKeyDown("space") && IsGrounded)
{
Rbody.AddForce(Vector3.up * JumpHeight * Time.deltaTime);
anim.SetBool("Jump", true);
}
else
{
anim.SetBool("Jump", false);
}
}
public bool IsGrounded;
void OnCollisionStay(Collision collisionInfo)
{
IsGrounded = true;
}
void OnCollisionExit(Collision collisionInfo)
{
IsGrounded = false;
}
Answer by Paul-Jan · Dec 12, 2016 at 03:45 PM
Transform has a very handy function for that, called Transform.TransformDirection . You can use it do convert your local velocity vector to the correct vector in World Space.
var localVelocity = new Vector3(moveX, Rbody.velocity.y, moveZ);
Rbody.velocity = transform.TransformDirection(localVelocity);
Your answer
Follow this Question
Related Questions
Set rotation based on 2 points problem 1 Answer
Rotate but keep direction 1 Answer
rotate vector around local axis 2 Answers
How can I move an object to click point in 2D? 0 Answers
Move object on local axis instead of world axis after rotation 0 Answers