Ali Salehi
Ali Salehi

Reputation: 341

Move the player and then change the scene

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.

Upvotes: 3

Views: 303

Answers (1)

Jinjinov
Jinjinov

Reputation: 2683

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
        }
    }
}

Upvotes: 1

Related Questions