Assuming you want to set the y-axis (that is, make your object rotate along the xz-plane only), you simply execute
Transform::LookAt
by passing as a parameter a new vector in which the x and y coordinates are of the object- target and the y coordinate of the object itself being rotated.
In this example (in C #), suppose that this script is attached to the object being rotated (the cannon) and that there is another object (the enemy that the cannon should hit) that has been linked via editor to the enemy property:
using UnityEngine;
using System.Collections;
public class RotateTowards : MonoBehaviour {
public Transform enemy;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 vTarget = new Vector3 (enemy.position.x, transform.position.y, enemy.position.z);
transform.LookAt(vTarget);
}
}
Thus, with each frame of the game, a new vector almost equal to the enemy position vector (differing only in the y axis, where the cannon coordinate was maintained) is passed to the LookAt
method (which will cannon in order to "point" to the position in the given space).
Important: Note that in Unity the convention is that the z-axis points to the front of the object, so functions like LookAt
(freely translating: "look at") are based on that vector for the calculations. If your object is not rotating as you wish, you should modify it so that the "front" part is pointing to the z-axis (maybe there is some way to automatically adjust this in Unity, but I honestly do not know - I know this is defined externally in the 3D tool used in modeling the character or game object).
This example I suggested requires that the enemy be linked to the cannon, but in a real game this is not usually done this way because there are different enemies. In this case, the suggestion to use a collider is nice because you can receive collision events and rotate the cannon to the (enemy) object that has entered the "threat area". The best collider for your case seems to be even a ball centered on the cannon, whose radius is set to define your range.
There is also the possibility of creating a global list of enemies and checking for each one if they fall short of a pre-defined circular distance, but this ends up being a proper implementation of a crash test. >