Moving a Door in a Unity VR Game

Does your game need a door for players to enter? Learn how to build a door and implement player movement from scratch in this free tutorial!

When the player looks at Button, we want Door to move down and to have Player move inside the castle. Let’s implement Button to lower Door.

In this tutorial:

Setup

To follow along, you’re going to need a Unity virtual reality project open with a basic room set up for the player to enter through its door. If you need help setting up such a Unity project, go to our previous post Building a Castle in a Unity VR Game.

We’re using Unity v5.4.3f1. If you’re using a different version of Unity and find an incompatibility, drop us a comment down below with your question.

Step 1: Writing a Door C# Script

To make our door move up and down to open, we will give it custom logic. That means writing a C# script!

In the Assets folder, create a C# script named “Door”. Select the Door object from the Hierarchy. Drag and drop the Door script to the Inspector.

Open Door.cs. In the door class, declare the following variable. It will hold a reference to the door’s open position.

private Vector3 targetPosition;

targetPosition is a Vector3. The Position, Rotation, and Scale properties in the Transform component are Vector3’s. They store a value in the X, Y, and Z axes. We will use what is stored in targetPosition to make Door move to targetPosition.

mountain illustration with a flag at the peak
Next we will set the door’s target position.

Step 2: Setting the Target Position

At the beginning of the Door script, we need to set targetPosition to the Door object’s current position. If we did not, targetPosition would be Vector3.0. Door would move to the position 0 0 0.

In the Start method, use the following code to save the Door object’s current position in targetPosition. In this code:

  • We use the transform keyword to access Door’s Transform component (in the Inspector)
  • We use the position keyword to access the Position property of that Transform component.
  • We take the value of the Position property and assign it as the value of targetPosition.

void Start () {
    targetPosition = transform.position;
}

Step 3: Building Movement Logic

Now we will program the actual movement logic. Type the following code in the Update method.

void Update() {
   transform.position = Vector3.Lerp(transform.position,        targetPosition, time.deltaTime);
}

transform.position = makes an assignment. We will save what is to the right of the equals sign in the property that is to the left of the equals sign.

Making a Lerp is a linear interpolation. It is like we are making an animation that is going from Door’s current position to targetPosition.

  • The first parameter of Lerp, transform.position, is Door’s source position.
  • The second parameter, targetPosition, is Door’s destination position.
  • Door will move from transform.position to targetPosition in Time.deltaTime.

In the Door class, create the following variable to define the position of Door when it is lowered.

public Vector3 loweredPosition;

Below the Update method, declare the method LowerDoor.

public void LowerDoor () {

}

In this  method, set targetPosition to equal loweredPosition.

public void LowerDoor () {
   targetPosition = loweredPosition;
}

Save the script, and open Unity. You can set the Lower Position property of Door in Door’s Script component in the Inspector. Set the XYZ values of Lowered Position to 0 -5 0.

changing script values in the inspector
In the Inspector, you can change variables set in the script.

Step 4: Making a Door Button

Now we will access Button and make it lower Door. Create a C# script in the Assets folder. Name the script “DoorButton”. Double-click on the script to open it.

In the DoorButton class, declare the variable door. This variable will reference the lowering door.

public Door door;

Below the Update method, define the method OnLook. OnLook will be called when a player looks at DoorButton.

public void OnLook () {

}

Inside OnLook(), call the LowerDoor method on door.

public void OnLook () {
door.LowerDoor ();
}

When the player looks at the button, DoorButton will order Door to lower.

Save DoorButton.cs, and open Player.cs.

So far, in the Update method, we are printing the object that the player is looking at. Instead we want to identify if we are looking at DoorButton. If we are, we want Door to lower.

Type the following if block to access the Transform component of the object the player is looking at. Call GetComponent to retrieve any component that the object can have, such as Transform or Mesh Renderer.

In this case, get the component DoorButton. There is a DoorButton component when the player is looking at DoorButton. The parentheses are for the method call. The if block will run code if the DoorButton component is not null.

void Update () {
Raycast hit;

if (Physics.Raycast(transform.position, transform.forward, out hit) {
if (hit.transform.GetComponent<DoorButton> () != null) {

}
}
}

If the condition passes, call the OnLook method on DoorButton. This will allow the script to recognize when the player looks at the door button.

if (hit.transform.GetComponent<DoorButton> () != null) {
hit.transform.GetComponent<DoorButton> ().OnLook ();
}

Let’s test to see if this works! Save the script, and open Unity. Press Play. Move the camera until the crosshair is on the Button game object in the Scene.

recognizing a raycast as user touch
Uh-oh, our method isn’t working!

Nothing will happen. To determine what went wrong, we can print log messages every time a step of the code should happen.

Step 5: Debugging

Open Player.cs. Above the OnLook method call, print the message “Looked at door button!”

if (hit.transform.GetComponent<DoorButton> () != null) {
Debug.Log("Looked at door button!");
hit.transform.GetComponent<DoorButton> ().OnLook ();
}

Let’s also include a log statement in the DoorButton script, to see if that code is working. Save the current script, and open DoorButton.cs. In the OnLook method, print the message “Button lowering door!”

public void OnLook () {
Debug.Log("Button lowering door!");
door.LowerDoor ();
}

To make sure we cover all our bases, let’s add a log line to the Door script as well. Save the DoorButton script, and open Door.cs. In the LowerDoor method, print the message “Lowered door!”

public void LowerDoor (){
Debug.Log ("Lowered door!");
targetPosition = loweredPosition;
}

Save the script, and open Unity. Press Play. No messages will print in the console. What could be the reason?

Stop playing the scene.

Another debugging step is to click through each object in the Inspector and make sure it has the necessary fields connected. If you do this, eventually you will come to the Button object, and you will see that it does not contain a DoorButton script!

We have our solution! Drag and drop the DoorButton script to the Button game object’s Inspector. Drag and drop the Door object from the Hierarchy to the Door property of the Door Button (Script) component.

connecting a script into unity
You must connect the script to the game object

Press Play. Look at Button by moving the crosshair on top of the Button object. Door will lower. The console will print “Looked at door button!”, “Button lowering door!”, and “Lowered door!”

raycasting working in unity
Our Debug lines are printing as expected!

Also, the door is moving down when the raycast touches it. That means success! We’ll continue this game in the next post… unless you object…. What tutorials do you want to see next? Drop a comment below.

Review

—Team Mammoth from Mammoth Interactive INC. Tutorial by Glauco Pires and Transcribing by Alexandra Kropova

Liked this tutorial? Get a free game development video course!

Leave a Reply

Your email address will not be published. Required fields are marked *