Question

I am making an object move in it's update() and turn left right up down according to user input. All I want is to make a spotlight follow the object. Object's Rotation: 0,180,0 SpotLight's Rotation: 90,0,0 Since the rotations are different( and they need to be like that), I cannot make the light follow the object. code :

function Update () {

    SetControl(); // Input Stuff... 

    transform.Translate (0, 0, objectSpeed*Time.deltaTime);

    lightView.transform.eulerAngles=this.transform.eulerAngles;
    lightView.transform.Rotate=this.transform.eulerAngles;
    lightView.transform.Translate(snakeSpeed*Time.deltaTime,0, 0);  //THIS IS INCORRECT

}

lightView is simply pointing to the SpotLight.

Était-ce utile?

La solution 2

All I want is to make a spotlight follow the object.

This is a two-step process. First, find the coordinate position (in world coordinates) of your target. Second, apply that position plus an offset to your spotlight. Since your light is rotated 90° along the x-axis, I assume your light is above and looking down.

var offset = new Vector3(0, 5, 0);

function Update()
{
  // Move this object
  transform.Translate (0, 0, objectSpeed*Time.deltaTime);

  // Move the light to transform's position + offset.
  // Note that the light's rotation has already been set and does
  //  not need to be re-set each frame.
  lightView.transform.position = transform.position + offset;
}

If you want a smoother "following" action, do a linear interpolation over time. Replace

lightView.transform.position = transform.position + offset;

with

lightView.transform.position = Vector3.Lerp(lightView.transform.position, transform.position + offset, Time.deltaTime * smoothingFactor);

where smoothingFactor is any float.

As an aside, it is near death to call transform.* in any kind of recurring game loop, because GameObject.transform is actually a get property that does a component search. Most Unity documentation recommends you cache the transform variable first.

Better code:

var myTrans = transform;    // Cache the transform
var lightTrans = lightView.transform;
var offset = new Vector3(0, 5, 0);

function Update()
{
  // Move this object
  myTrans.Translate (0, 0, objectSpeed*Time.deltaTime);

  // Move the light to transform's position + offset.
  // Note that the light's rotation has already been set and does
  //  not need to be re-set each frame.
  lightTrans.position = myTrans.position + offset;
}

Autres conseils

What your looking for is the Unity method Transform.lookAt.

Place the following script on the spotlight. This code will make the object it is attached to, look at another object.

// Drag another object onto it to make the camera look at it.
var target : Transform; 

// Rotate the camera every frame so it keeps looking at the target 
function Update() {
    transform.LookAt(target);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top