- Home /
Simple object rotation & LookAt
Hi, I am trying to simply rotate an object along the X axis while also getting the object to look at my mouse position on it's Y axis, I can get each of these to work on there own f I comment one of the parts out but if I leave both in, the rotation doesn't happen and only the LookAt function will continue to work. Hopefully you can see what I am trying to do? So they may be a better way to do this.
Here is my code sample:
using UnityEngine;
using System.Collections;
public class movementControler : MonoBehaviour
{
public GUIText testData;
public GameObject sphere;
float speed = 0.15f;
private float mouseX, mouseY;
private Vector3 worldPos;
private float cameraDif;
float xRot;
// Use this for initialization
void Start ()
{
cameraDif = camera.transform.position.y - sphere.transform.position.y;
xRot = sphere.transform.localRotation.x;
}
// Update is called once per frame
void Update ()
{
mouseX = Input.mousePosition.x;
mouseY = Input.mousePosition.y;
worldPos = camera.ScreenToWorldPoint(new Vector3(mouseX,mouseY,cameraDif));
if(Input.GetMouseButton(0))
{
//When using both, only LookAt works, but using them by themselves works how I want.
sphere.transform.eulerAngles = new Vector3(-xRot++,0,0);
sphere.transform.LookAt(worldPos);
}
}
}
There are some issues here. First localRotation is a Quaternion...a 4D construct where the x,y,z, and w components don't represent angles. Second, you need to describe the exact behavior you want in combining these two rotations. As you found out, LooAt() sets all three axes, so fixing the issue will depend on getting a very clear description of your desired behavior.
All I want to achieve is a constant rotation along the objects local x axis while having the y axis follow the location of the mouse.
Should I be adding the rotational value to the xAxis that I want before applying the LookAt?
Answer by robertbu · Apr 15, 2014 at 07:48 PM
The way you have things structured here makes writing an answer a bit more difficult. My suggestion is that you have two game objects for your sphere, 1) an empty game object as a parent, and 2) the physical object as the child. 'sphere' would refer to the empty game object, and 'sphereChild' the physical game object. You would add the following at line 29:
worldPos.y = sphere.transform.position.y;
This change will result in the parent (empty) game object only rotating on the 'y' axis.
The physical object (child) would then have this happen:
xRot += speed * Time.deltaTime;
sphereChild.transform.localEulerAngles = new Vector3(xRot,0,0);
This works great thank's. Now my object gains a constant rotation along the xAxis while constantly tracking the mouse on it's yAxis.