- Home /
How to Rotate on one axis?
So I'm trying to rotate an object on only the Y axis here is the code I got.
var lookDirectiony = player.position.y - transform.position.y;
transform.Rotate(0,lookDirectiony,0);
I've tried several ways to do this but the enemy will normally start flying around. How do I only rotate it on ONE axis and make sure it stays on the ground? It already has a rigidbody with gravity and mass. That code that I made doesn't rotate it for some reason.
Answer by aldonaletto · Jul 17, 2012 at 02:23 AM
You're confusing things: lookDirectiony is a distance, while Rotate requires an angle in degrees. If you want the enemy to look in the player direction, you can just use LookAt like DaveA suggested:
transform.LookAt(player);
But this may tilt the enemy when the player is at a different height, thus a little more coding may be necessary:
var lookDir = player.position-transform.position;
lookDir.y = 0; // keep only the horizontal direction
transform.rotation = Quaternion.LookRotation(lookDir);
this will align the enemy forward direction (the blue axis) to the vector lookDir, which became strictly horizontal because its Y coordinate was zeroed - thus effectively rotating the enemy strictly around the Y axis.
The problem I was having was keeping the AI on the ground. I figured that it'd be because of the rotation, but it wasn't. So I've fixed all the problems. Thanks for the feed back and helping me solve my problem!
Answer by herman111 · Jul 22, 2014 at 01:45 PM
using UnityEngine;
using System.Collections;
public class RotateOBJ : MonoBehaviour {
// Speed it goes around.
public int rotateSpeed = 5;
void Update () {
// Rotate around the (z) axis.
transform.Rotate(0 ,0 ,rotateSpeed * Time.deltaTime);
}
}
Answer by Claudioteles85 · Apr 11, 2019 at 12:31 PM
By default when you rotate, all rotate.x,y,z axis moves. This is especially evident when rotate.x does not equal 0. If you want to rotate the game Object relative to the World and not relative to Self make use to add Space.World at the end of transform.Rotate
float horizontalMove = moveSpeed * Input.GetAxis("Mouse X");
transform.Rotate(0, horizontalMove, 0, Space.World);
Answer by DaveA · Jul 16, 2012 at 08:38 PM
This may be some help: http://docs.unity3d.com/Documentation/ScriptReference/Transform.LookAt.html
Your answer
Follow this Question
Related Questions
Rotating on X and Z axis only 2 Answers
Slerp Problem?: Enemy in Constant Rotation! 1 Answer
camera rotation 0 Answers
Move the Object to Camera respective. 1 Answer
How to lock Y Rotation 3 Answers