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;

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.

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:


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.

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);


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);

This may be some help: Unity - Scripting API: Transform.LookAt