- Home /
How can I rotate my player to look at the direction my Joystick is pointing to? (Top-Down 2D)
Top-Down 2D:
How can I rotate my player to look at the direction my Joystick is pointing to?
Here is the code that I'm using for my Joystick. It moves my tank properly but at the same rotation (as expected, since I have not coded it yet to rotate/look at the position I'm moving towards to)
Vector3 tempJoyDelta;
public static Vector3 joyDelta;
Vector3 touchPosition;
public Transform centerPos;
Ray ray;
int currTouch = 64;
int sprintMask;
bool moving;
float saucerSpeed;
public GameObject tank;
void Awake () {
speed = 1.0f;
sprintMask = 1 << 8;
}
void Update () {
if(Input.touchCount > 0)
{
for(int i = 0; i < Input.touchCount; i++)
{
currTouch = i;
ray = Camera.main.ScreenPointToRay(Input.touches[i].position);
if(Physics.Raycast(ray, Mathf.Infinity, sprintMask))
{
if(Input.GetTouch(currTouch).phase == TouchPhase.Began && !moving)
{
moving = true;
}
if(Input.GetTouch(i).phase == TouchPhase.Ended || Input.GetTouch(i).phase == TouchPhase.Canceled)
{
moving = false;
}
if(Input.GetTouch(i).phase == TouchPhase.Moved || Input.GetTouch(i).phase == TouchPhase.Stationary)
{
touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(Input.GetTouch(i).position.x, Input.GetTouch(i).position.y, 0));
}
}
}
}
if(moving)
{
joyDelta = centerPos.position - touchPosition;
joyDelta.z = 0;
tank.transform.Translate(((Vector3.forward * joyDelta.y) * speed) * Time.deltaTime);
tank.transform.Translate(((Vector3.right * joyDelta.x) * speed) * Time.deltaTime);
}
}
Thanks!
Answer by Itaros · Oct 24, 2014 at 06:44 AM
Take the vector at which joystick is pointed and use math to get heading:
float heading = Mathf.Atan2(joyvector.x,joyvector.y);
It is heading in radians which can be used to point the object in right direction like:
transform.rotation=Quaternion.Euler(0f,0f,heading*Mathf.Rad2Deg);
its working fine but rotation is not smooth,there are jerks on every rotation.Please help
Answer by KingKong320 · Apr 20, 2018 at 04:18 AM
if (moveVec.sqrMagnitude > 0.1) {
angle = Mathf.Atan2 (moveVec.x, moveVec.y) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.Euler (new Vector3 (0, 0, -angle)), Time.deltaTime * rotationSpeed);
}
i have got from somewhere it can be achieve like this. Thankyou @InvisionaryU$$anonymous$$ :)
Answer by InvisionaryUK · Apr 19, 2018 at 11:15 AM
@meticodetest Just use interpolation between angles this should smooth it out for you. il get an example up as soon as i can
hi, can you explain how to smooth rotation, please?
Your answer
Follow this Question
Related Questions
Find left joystick Vector2 away from sprite's up direction. 1 Answer
Updating rotation of client not working - strange error 0 Answers
Character rotation and move to mouse click point with speed 0 Answers
Problem when rotating sprite and moving it foward 1 Answer
Rotating an object towards target on a single axis 2 Answers