Hi
I’m doing a top down game and would like my player to look in the direction he is going in. I have found some code that changes the players rotation which to me looks like it should move the player.
I have also got some code that will move the player backwards and forwards, left and right but I can’t merge the two different section of code together which makes me think there must be another way and after looking at everyoones else’s questions and solutions, I am stumped.
This changes my rotation:
`
void Update()
{
if (Input.GetKeyDown (KeyCode.W))
transform.forward = new Vector3 (0f, 0f, 1f) * speed * Time.deltaTime;
else if (Input.GetKeyDown(KeyCode.S))
transform.forward = new Vector3(0f, 0f, -1f);
else if (Input.GetKeyDown(KeyCode.D))
transform.forward = new Vector3(1f, 0f, 0f);
else if (Input.GetKeyDown(KeyCode.A))
transform.forward = new Vector3(-1f, 0f, 0f);
}
`
and this allows me to move:
if (Input.GetKey (KeyCode.UpArrow))
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.DownArrow))
{
transform.Translate(Vector3.forward * -speed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.RightArrow))
{
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}
Two different pieces of code which both do jobs I would like to do. They won’t work together or even be in the same script as each other.
I have tried
transform.forward = new Vector3 (0f, 0f, 1f) += transform.Translate(Vector3.forward * -speed * Time.deltaTime;
I have also tried
transform.position += person.transform.forward * Time.deltaTime * speed;
but it won’t have it. I think i’m close but I am out of ideas.
Please help if you can.
Harry
PS I know the inputs are different, its not like that in my code. I back my code up as I create and find it, this is the back up which hasn’t been changed to match.
EDIT:
Why won’t this work?
private Vector3 direction; //something like this??
void Update()
{
if (Input.GetKey (KeyCode.UpArrow))
{
direction = transform.Translate(Vector3.forward * speed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(direction);
}
}
I know this moves the player transform.Translate(Vector3.forward * speed * Time.deltaTime); so wouldn’t I be able to use this with transform.rotation = Quaternion.LookRotation() to change the rotation.