3
votes

I have a problem. I want that if player click on StudyOutDoor, first the object move toward to the door, then change the scene in Unity. here is my code:

if (Physics.Raycast (clickPoint, out hitPoint)) {
                    if (hitPoint.collider.name == "StudyOutDoor") {
                        target.y = transform.position.y;
                        target.z = transform.position.z;
                        transform.position = Vector3.MoveTowards (transform.position, target, playerSpeed * Time.deltaTime);
                        sceneNumber = 3;
                        Application.LoadLevel("Corridor");
                    }

But it is just changing the scene without moving toward to the position I said. Please help.

1
Yea, calling MoveTowards moves your player in the data at the moment of calling. But the visuals are only going to be updated after the current frame ends. That never happens because you immediatly load the next scene. Seems like you want to move the player smoothly to the target. right now your player moves to the target in about 0.016 seconds. Using coroutines would probably be the most efficient solution. - Noel Widmer

1 Answers

1
votes

the object does move toward the door, you just don't see it because you load the new level in the same frame. what happens in detail:

  1. new frame starts
  2. ray is cast and hit
  3. you assign target position
  4. you change transform position toward the target position
  5. the level start loading
  6. new frame starts

what you want to do:

  1. new frame starts
  2. ray is cast and
  3. you assign target position
  4. you change transform position toward the target position
  5. new frame starts
  6. you repeat step 4. until object reaches target position (this lasts many frames)
  7. when object reaches target position, you load new level

to achieve this, you should set a bool flag that moves the object only when the ray was hit

pseudo code:

update()
{
    if( ray cast hit )
    {
        calculate target position
        set flag to true
    }
    if( flag )
    {
        move object to target position
        if( object reached target position )
        {
            load new level
        }
    }
}