- Home /
[Solved] Rotating with lookat on 2D
I'm trying to rotate an object on 2D unity on android, just pretend to look at the position of the touch, but when i do the lookat, the object gets crazy and rotate on angle x and y but no z. My code is simple:
if(Input.GetMouseButton(0)){
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = 0;
this.transform.LookAt(pos);
}
What am i doing wrong?
is the object you want to look at the position of the click also on position.z = 0? because if it isn't that would make it move in all angles, if it is at the same z position then it would only change on the x and y axis.
All my objects are on z=0. Does not have to change the rotation on z axis? If i can only move on x and y, the rotation should be i think on z axis. I don't see the sense rotating x and y.
Answer by Pyrian · May 06, 2014 at 12:35 AM
I never got LookAt to work, either. Arctangent does the job, though. Here's a snippet from my code (CurFlip is just 1 or -1 based on whether the sprite's X scale is 1 or -1 at the time):
transform.rotation = Quaternion.Euler (0.0F, 0.0F, Mathf.Atan2 ((CurY - transform.position.y) * CurFlip, (CurX - transform.position.x) * CurFlip) * Mathf.Rad2Deg);
Didn't work neither. It point only to one side (right or left depending on CurFlip) on PC, and Android only rotate a few pixels. I'm trying everything i can see and don't get anything.
Well, that's a straight copy of working code - tested on PC, web, and Android. The symptom you describe sounds like you left out the "* $$anonymous$$athf.Rad2Deg" at the end, or just aren't getting a valid y for whatever reason.
I tried the code on my laptop and worked fine. But when i execute on an android device it just face every time to the same point (i show the coordinates of the touch point and it works fine) $$anonymous$$y code for android is:
else if(SystemInfo.deviceType == DeviceType.Handheld){
if(Input.touchCount > 0){
Vector2 touchPos = Input.GetTouch(0).deltaPosition;
Vector3 pos = Camera.main.ScreenToWorldPoint(touchPos);
pos.z = this.transform.position.z;
float CurFlip = 1.0f;
float atan = $$anonymous$$athf.Atan2 ((pos.y - transform.position.y) * CurFlip, (pos.x - transform.position.x) * CurFlip) * $$anonymous$$athf.Rad2Deg;
transform.rotation = Quaternion.Euler (0.0F, 0.0F, atan);
Acelerate(); // Add force to the object
}
}
I'm getting mad with android...
You're using deltaPosition where you should be using position.
I just see it and was going to post it. This change fix the problem. I changed so many times my code i forget to chang that... So that is it. Problem solved. Thank you all.
Your answer
Follow this Question
Related Questions
2D LookAt not working as intended 1 Answer
LookAt() not working with mouse as target in 2D 1 Answer
BOX ROTATE ONLY ON X AXIS When Look AT!!HELP! 0 Answers
2D Sprite Rotation 0 Answers