- Home /
Rotate object in 45 degree steps
Hello! I have a 2D character which only has graphics for 45° rotations. That means: top, topright, right, downright, down, etc ..
I want to character rotate to the cursor. I have the vector from the character's position to the cursor's position in the world. Only x and z matters to me here. How do i find out the closest possible direction (top, topright,..) from that vector?
The code for this so far:
var hit : RaycastHit;
var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)) {
Debug.DrawLine (transform.position, hit.point);
cursorWorldPos = hit.point;
cursorWorldPos.y = transform.position.y;
aimingDirection = cursorWorldPos - transform.position;
Answer by robertbu · Aug 23, 2013 at 04:54 AM
One solution is to use Mathf.Atan2():
#pragma strict
function Update() {
var hit : RaycastHit;
var ray : Ray = camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)) {
Debug.DrawLine (transform.position, hit.point);
var cursorWorldPos = hit.point;
var aimingDirection = cursorWorldPos - transform.position;
var angle = -Mathf.Atan2(aimingDirection.z, aimingDirection.x) * Mathf.Rad2Deg + 90.0;
angle = Mathf.Round(angle / 45.0f) * 45.0f;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
}
}
Note if the camera is looking straight down, then you don't need the raycast. You can use ScreenToWorldPoint():
#pragma strict
function Update() {
var pos = Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.y - transform.position.y);
pos = camera.main.ScreenToWorldPoint(pos);
var aimingDirection = pos - transform.position;
var angle = -Mathf.Atan2(aimingDirection.z, aimingDirection.x) * Mathf.Rad2Deg + 90.0;
angle = Mathf.Round(angle / 45.0f) * 45.0f;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
}
If the camera is at an angle, then it would be somewhat more efficient to do a Collider.Raycast(). It would be even more efficient to do a Plane.Raycast().
wow, i never would have found this solution by myself. thank you!
Your answer
Follow this Question
Related Questions
What is the most efficient way to rotate an object? 3 Answers
Rotation: rotate by a defined angle 1 Answer
Problem with "if or" statement. 1 Answer
How can I rotate an object with certain degrees? 2 Answers
Rotating Player 0 Answers