- Home /
Question by
Ernesto518 · Jul 10, 2014 at 02:10 AM ·
vector3quaternionoffseteuler
c# I want to lookat/rotate in only the Z axis so my object doesnt turn on its side/always faces camera
public float moveSpeed = 1.0f;
public GameObject lazer;
public float lazerSpeed = 1.0f;
public float shootDelay = 0.2f;
private bool canShoot = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
transform.position += moveDirection * moveSpeed * Time.deltaTime;
if((Input.GetAxis("FireHorizontal") != 0.0f || Input.GetAxis("FireVertical") != 0.0f) && canShoot)
{
Vector3 shootDirection = new Vector3(Input.GetAxis("FireHorizontal"), Input.GetAxis ("FireVertical"), 0).normalized;
GameObject lazerInstance = Instantiate(lazer, transform.position, Quaternion.LookRotation(shootDirection)) as GameObject;
lazerInstance.rigidbody.AddForce (shootDirection * lazerSpeed, ForceMode.VelocityChange);
canShoot = false;
Invoke ("ShootDelay", shootDelay);
}
}
void ShootDelay()
{
canShoot = true;
}
}
Quaternion.LookRotation works but rotates object so camera can not see sprite because it is turned sideways.
Comment
Answer by robertbu · Jul 10, 2014 at 02:13 AM
The easiest thing for 2D is:
Vector3 shootDirection = new Vector3(Input.GetAxis("FireHorizontal"), Input.GetAxis ("FireVertical"), 0).normalized;
float angle = Mathf.ATan2(shootDirection.y, shootDirection.x) * Mathf.Rad2Deg;
GameObject lazerInstance = Instantiate(lazer, transform.position, Quaternion.AngleAxis(angle, Vector3.forward)) as GameObject;
Note this solution assumes you are rotating a sprite or a Quad and that the right side of the object is the side considered 'forward'. If 'up' is considered forward, add 90.0f to 'angle' before using it in AngleAxis().
Thank you very much! Spent hours on this. you are pro.
Your answer
Follow this Question
Related Questions
Quaternion.LookRotation with an offset. 1 Answer
Quaternion.Euler rotations don't add up 0 Answers
Problem with rotation around axis 1 Answer
Raycasting at an offset angle? 4 Answers
Rotate some coordinates in relation to an object's rotation 0 Answers