Hello Guest

Author Topic: Rotating on the Z Axis to Face Objects  (Read 5970 times)

ConceptMotion

  • Newbie
  • *
  • Posts: 2
    • View Profile
Rotating on the Z Axis to Face Objects
« on: November 22, 2013, 07:46:39 pm »
So, I've been struggling with this issue for a few days. I am building a top down 2D game and basically I want to have a sprite face another sprite by rotating on the Z axis (I also need the player sprite to look at the mouse, which is part of the same problem). However, the sprites are designed top down; facing the top of the characters head, so the "face" of the character is actually on the sides facing the X and Y axes (the vertical axis for the game world is along the Z axis). So, when I try to use PlayMaker, or custom scripts to rotate the sprites towards objects, it rotates the front (the top of the head facing the Z axis) towards the objects, which turns the sprites sideways and making them look flat. Is there anyway around this?
« Last Edit: November 22, 2013, 09:39:47 pm by ConceptMotion »

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Rotating on the Z Axis to Face Objects
« Reply #1 on: November 22, 2013, 10:45:23 pm »
This answers the question, specifically the part about assigning the z euler angle.
http://answers.unity3d.com/questions/508685/rotate-object-on-z-axis-to-face-current-mouse-posi.html


ConceptMotion

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Rotating on the Z Axis to Face Objects
« Reply #2 on: November 23, 2013, 11:35:03 pm »
Excellent! Thank you very much!

Just in case anyone else is having this issue, here is my code:

Code: [Select]
using UnityEngine;
using System.Collections;

public class LookAtMouse : MonoBehaviour {

public Camera camera;
private Vector3 mousePosition;

void Update() {

//Gets the current mouse position on the screen
mousePosition = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Input.mousePosition.z - camera.transform.position.z));

//Rotates the object towards the mouse cursor
rigidbody.transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2((mousePosition.y - transform.position.y), (mousePosition.x - transform.position.x)) *Mathf.Rad2Deg - 90);

}
}

This basically rotates the attached GameObject to your current mouse position. Just make sure to attach your main camera to the script in the inspector, and also make sure to have a Rigidbody component attached to the GameObject.

Thanks again!