I’m making a game where there are spinning spike spheres which have one eye on the middle as you see in the picture down below. And I want the eye look at the player all the time. I already have some code in c# which makes the eye work when the enemy isn’t moving, but when the enemy moves the eye does’t follow because I don’t know how make the eye follow along with the enemy. And yes the eye is a child object of the enemy.
Use Pupil.localPosition
instead of Pupil.position
. position
sets object’s position in the world space, while localPosition
sets the position inside its parent object. You are calculating the eye position inside your enemy object, so you want the localPosition
here.
EDIT
To make the answer clearer - the original code remembers the world position of the “Pupil” (with no relation to its parent “Eye”), and in the Update
method that stored position is used to calculate where the “Pupil” should look. This works fine, as long as the “Eye” remains stationary. When the “Eye” moves, the stored world position of the “Pupil” is no longer valid - it remains in the original place, when the “Eye” has moved on.
In Unity, when one object is a child of another and the parent object is moved, the child object is moved with it to keep its position. This is why child objects have a transform.localPosition
property - so we can modify the relative position of the child object while letting Unity still update its world position when the parent object moves.
If we change the code above to the localPosition
version:
void Start() {
mPupilCenterPos = Pupil.localPosition;
}
void Update() {
Vector3 lookDir = (Player.position - mPupilCenterPos).normalized;
Pupil.localPosition = mPupilCenterPos + lookDir * eyeRadius;
}
the child object will still follow the parent object, but now the lookDir
calculation is broken - we are comparing Player.position
, which is the world position of the player, with a local position of the enemy. We need to change that and convert the local pupil center to its world space value. To do that, we simply add it to its parent’s world position:
Vector3 lookDir = (Player.position - (transform.parent.position + mPupilCenter)).normalized;
Hi please send me your eye script