- Home /
Top down movement and rotation
I am trying to make a top down game where the player is able to loo and move only in a 2d field. My issue is my code makes them move like so:
enter code here
if(Input.GetAxis("Horizontal") > 0)
{ myTransform.Translate(new Vector3 (speed ,0 ,0) * Time.deltaTime); }
if (Input.GetAxis("Horizontal") < 0) { myTransform.Translate(new Vector3 (-speed ,0 ,0) * Time.deltaTime); }
if(Input.GetAxis("Vertical") > 0) { myTransform.Translate(new Vector3 (0 ,speed ,0) Time.deltaTime); } if (Input.GetAxis("Vertical") < 0) { myTransform.Translate(new Vector3 (0 ,-speed ,0) Time.deltaTime); }
}
enter code here
What i want is to be able to press "wsad" and make the character move accordingly and not relevant to where it is facing. On top of that I want the character to be facing the mouse:
enter code here
myTransform.LookAt(new Vector3 (ScreenMousex, (Screen.height - ScreenMousey), 0))
enter code here
This doesn't seem to work. Any ideas?
Answer by asafsitner · Jul 10, 2012 at 07:17 AM
You can specify the space in which the object translates. You need to explicitly set it to 'world' as it is set to 'self' by default.
Try something like this for translation:
myTransform.Translate(new Vector3 (Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")) * Time.deltaTime);
To look at the mouse I suggest you implement `Camera.ViewportToWorldPoint`.
Answer by The-Arc-Games · Jul 10, 2012 at 07:21 AM
Your code is basically unreadable, please try a bit harder next time to make it easier to help you.
You're on the right track, but translate is 'self' oriented by default. Here's the guide's code for getaxis, which we change slightly:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public float speed = 10.0F;
void Update() {
float vertical = Input.GetAxis("Vertical") * speed;
float horizontal = Input.GetAxis("Horizontal") * speed;
translation *= Time.deltaTime;
transform.Translate(0, 0, translation, Space.World);
transform.LookAt(new Vector3 (ScreenMousex, (Screen.height - ScreenMousey), 0));
}
}
We just assume you're already transforming mouse into world in the lookat, otherwise check ScreenToWorldPoint