unity rotate object

Unity Rotate Object With Mouse: FREE Tutorial #5 Multiplayer MMO Game

Unity 3D MMO Tutorial Series

Welcome to the Unity Rotate Object With Mouse MMO Game Tutorial. You have made it to tutorial number 5. If you have not completed the fourth tutorial, go back and finish it. You can find the tutorial here. If you are looking for the first tutorial, you can find it here.

Most triple-A MMOs use the mouse as a secondary motion to the character movement system. The original “Star Wars Galaxies” only used the mouse for rotation.

Using the mouse for movement frees my hands to use the main number buttons for attacks. Mouse movement controls come in handy in becoming proficient in PVP.

The not-so-new “Star Wars The Old Republic” game uses this mouse movement. We will mimic this style of mouse controls in our game as well.

Star wars the old republic
SWTOR

Let’s Make A New Script

Right-click in the Scripts folder and create a new script named “MouseMovementControls.” Open the script file, and let’s begin coding!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseMovementControls : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

The first line of code references the “Player Character.” Being that the “Player Character” is a “GameObject,” We write the code at the top of the class:

GameObject player;

Because the script is a “MonoBehaviour,” we can attach it to our “GameObject Player.” In the Unity editor, click Add Component, just like in tutorial #2. Search for “MouseMovementControls,” and add it to the “Player.”

Now you should have an Inspector tab that looks like the picture below.

unity rotate object
MouseMovementControls

It’s Awake!

The next thing on the agenda is to delete the “Start()” method. We will use a different type of method in place of it. After you have deleted the “Start()” method, under the “GameObject player;” declaration, type the word “awake” and press “enter.”

Visual Studio will create a new method called “Awake().”

private void Awake()
{
        
}

The “Awake()” method is similar to “Start()” in that it will initialize what you put in it. However, “Start()” will initialize the code randomly. “Awake()” will prioritize the code in the order you code them. In this case, we want the script to prioritize a component first.

Now we need a reference to the “PlayerControls.cs” script. Our “MouseMovementControls.cs” script will not function without the main controls.

In the “Awake()” method, code the following:

playerControls = player.GetComponent<PlayerControls>();

You will receive an error because we haven’t declared “playerControls” yet. Under the “GameObject player;” declaration, type:

PlayerControls playerControls;

“PlayerControls” refers to the controls script we have written in the last few tutorials. We added the “playerControls” variable to point to the component associated with the other script. “[SerializedField]” is added to create a reference to the “Player.”

We can begin to script the method to our madness with the foundation set.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseMovementControls : MonoBehaviour
{
    [SerializeField] GameObject player;
    PlayerControls playerControls;
    private void Awake()
    {
        playerControls = player.GetComponent<PlayerControls>();
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

Save your script and drag the “Player” from the Hierarchy tab into the “Player” slot in the Inspector tab. Doing so tells the Unity editor what the object is. Unity will issue a null reference error if informing the editor is forgotten.

unity rotate object
Player Slot

GetMouseControls Unity Rotate Movement With Mouse

As you might have guessed, we will make a new method called “GetMouseControls().” Insert the code under the “Update()” method.

void GetMouseControls()
{
}

Let’s write the code to reflect the use of the left and right mouse buttons. The right mouse button will rotate the character in conjunction with the mouse’s left and right movements. The Left mouse button will make the character move forward in the direction the rotation vector is pointing.

Pressing the mouse button on the left alone will not make the character move. You must use the right mouse button in conjunction. The left mouse button will have another function involving the “character follow camera” later.

I want to go ahead and call the “GetMouseControls()” method so we don’t forget. In the “Update()” method, call the new method.

void Update()
{
    GetMouseControls();
}

As before with other methods, “GetMouseControls()” is called once every frame by the “Update()” method.

Are We Using The Mouse Buttons?

This section is where the fun begins. First, we will declare a couple of booleans. If you recall from previous tutorials, we made a couple of “bools” to help us decide if the question was “true” or “false.” You can read about booleans here.

At the top of the class, write two booleans. One for the left mouse button held and one for the right. Initialize both of the bools to “false.”

public bool isLeftMouseButtonHeld = false;
public bool isRightMouseButtonHeld = false;

Make the bools “public” to show a manual tick box in the Inspector.

unity rotate object
Mouse Button Confirmation

Let’s add the mouse buttons to the booleans. Reference the mouse button held using the “Input” method built into the Unity editor. “GetMouseButton(int button)” is the API for holding the mouse button. You can read about “GetMouseButton(int button)” here.

You can add the code to the “GetMouseControls()” method. Passing in a zero (0) will reference the left mouse button. Passing in one (1) will reference the right mouse button.

isLeftMouseButtonHeld = Input.GetMouseButton(0);
isRightMouseButtonHeld = Input.GetMouseButton(1);

We will start with the right mouse button in our code block. Write an “if” statement to check if the right mouse button was held down. To do this is very simple. In the method for “GetMouseControls()” type:

if (isRightMouseButtonHeld)
{
}

The code block is apparent. If the right mouse button is held, do something. Let’s do something.

In the above code block, insert the following:

isRightMouseButtonHeld = true;

This is temporary for now. Save the script and run the game. Make sure you have the “Player” selected in the Hierarchy and the mouse is in the game window. Hold the right mouse button down. If the code is correct and you have no errors, you will see the “Is Right Mouse Button Held” tick box is checked.

unity rotate object
Mouse Button Tick Box

Code Challenge!

Now that you know a little about coding in C#, write the code for the left mouse button. Make the”Is Left Mouse Button Held” box ticked as the left mouse button is held down. Don’t forget to save the script after you finish the code. Give it a try!

unity rotate object
Left Mouse Button Held

Ok, hopefully, you were successful in the challenge! If you had trouble, don’t worry. I’ve covered you. Type the following code below the code for the right mouse button held. (To be honest, whether or not you wrote the code, the left mouse button would still work because of the Unity API. We need the code we added to make the character do what we want.)

if (isLeftMouseButtonHeld)
{
   isLeftMouseButtonHeld = true;
}

Make The Character Move And Rotate With The Mouse

Now we will write the code to check both mouse presses simultaneously. The character can’t move forward unless both are “true.” The right mouse button rotates the character while the left mouse button moves the character forward.

We need a new boolean with the other booleans at the top of the class. The code holds a “true” or “false” value. Type or copy the following code:

public bool leftAndRightMouseButtons = false;

The code for the mouse buttons checks is similar to checking them individually. Write another “if” statement, such as the following code.

if ((isLeftMouseButtonHeld) && (isRightMouseButtonHeld))
{
    leftAndRightMouseButtons = true;
}

This code block checks to see if the left and right mouse buttons are held simultaneously.

Save the script and run the game. Press both mouse buttons and hold. Watch the tick boxes in the Inspector. Notice the three boxes ticked. Release the mouse buttons and notice the “Left And Right Mouse Buttons” box remains ticked.

unity rotate object
Left And Right Mouse Buttons

The stagnant tick box has an easy remedy. Add an “else” statement under the last “if” statement coded.

else
{
    leftAndRightMouseButtons = false;
}

Because we made the variable “false,” the code tells the editor that at least one of the mouse buttons is released.

Rotating The Character With The Mouse

The first line of code to rotate with the mouse is a “float” to hold the character angle. I named the variable a fittingly “characterAngle.” Add this code to the top of the class.

float characterAngle;

The next part of the code will access the character’s transform, which is, in other words, the X, Y, and Z values of “Player.” “Transform” is a Unity editor-specific method that pulls out the object’s location. Put this code somewhere at the top of the class, also.

public Transform character;

We need to write two more variables to hold the mouse rotation and the mouse rotation speed. The variables will be floats. At the top of the class, add these variables above the “float characterAngle;” variable.

public float mouseRotation;
public float mouseRotateSpeed = 5000f;

I set the rotation speed value high because the rotation should be fast. Play with the value when we have completed the computation to get a speed you are comfortable with.

A complicated calculation is the last bit of code needed to make the rotation happen. This formula will get the X axis of the mouse and multiply the rotation speed times “Time.deltatime.” Finally, the character rotation uses a “Quaternion” to find the character’s angle as the character rotates. You can read more about “Quaternion” here.

In the “if (isRightMouseButtonHeld)” statement, replace the code inside the curly brackets with the following two lines of code:

characterAngle += Input.GetAxis("Mouse X") * mouseRotateSpeed * Time.deltaTime;
character.localRotation = Quaternion.AngleAxis(characterAngle, Vector3.up);

If you run the game now, you will get an error. We will fix the error by dragging the “Player” from the Hierarchy tab into “Mouse Movement Controls” under “Character” in the Inspector tab. By doing this, we can track the “transform” of the character.

The error will disappear, and the character will properly rotate by using the right mouse button and moving the mouse.

Unity Rotate Object

What We Have So Far In Our Unity Rotate Object With Mouse Movement

Here is the code so far in the “MouseMovementControls” script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseMovementControls : MonoBehaviour
{
    public bool isLeftMouseButtonHeld = false;
    public bool isRightMouseButtonHeld = false;
    public bool leftAndRightMouseButtons = false;
    
    public Transform character;
    [SerializeField] GameObject player;
    PlayerControls playerControls;
    public float mouseRotation;
    public float mouseRotateSpeed = 5000f;
    float characterAngle;
    void Awake()
    {
        playerControls = player.GetComponent<PlayerControls>();
    }
    void Update()
    {
        GetMouseControls();
    }
    void GetMouseControls()
    {
        isLeftMouseButtonHeld = Input.GetMouseButton(0);
        isRightMouseButtonHeld = Input.GetMouseButton(1);
        if ((isLeftMouseButtonHeld) && (isRightMouseButtonHeld))
        {
            leftAndRightMouseButtons = true;
        }
        else
        {
            leftAndRightMouseButtons = false;
        }
        if (isRightMouseButtonHeld)
        {
            characterAngle += Input.GetAxis("Mouse X") * mouseRotateSpeed * Time.deltaTime;
            character.localRotation = Quaternion.AngleAxis(characterAngle, Vector3.up);
        }
        if (isLeftMouseButtonHeld)
        {
            isLeftMouseButtonHeld = true;
        }
    }
}

Forward Mouse!

We will add some code to the “PlayerControls.cs” script. The first thing we will do is add a reference to the “MouseMovementControls.cs” script. Type the following code just under the “Rigidbody rb;” reference.

MouseMovementControls mouseMovementControls;

Now we will add a “GameObject” to the script. The player character is the game object we are referencing. We need to do this because the keyboard has control of the “CharacterController.”

Under the other reference declarations, add the code to reference the player as a “GameObject.”

[SerializeField] GameObject player;

Drag the “Player” from the Hierarchy tab into the slot provided by the serialization of the code.

unity rotate object
Player Reference

Next, we will add an “Awake” method. Reference the “MouseMovementControls” before any other referenced objects to ensure the mouse movement doesn’t lag.

void Awake()
{
    mouseMovementControls = player.GetComponent<MouseMovementControls>();
}

Forward With The Mouse

I want you to change a variable name before we move “forward,” pun intended. Change the “public Vector2 keyboardInput;” by right-clicking the word “keyboardInput.” Rename the variable “movementInputs.” All variables of the same name will subsequently change along with it.

public Vector2 movementInputs;

The change will be even more apparent because both the mouse and the keyboard input will utilize it.

Now add the statement to make the mouse move the player object forward! Add an “if” statement that changes the “movementInputs.y” to 1. Place the code inside the “Locomotion()” method at the top.

if (mouseMovementControls.leftAndRightMouseButtons)
{
    movementInputs.y = 1;
}

The code is pretty straight “forward.” Pun intended again. The “leftAndRightMouseButtons” variable is passed in from the “mouseMovementControls” script.

Save the script file and run the game. The player character will move forward and rotate with the left and right mouse buttons!

What Does The PlayerControls.cs Script Look Like?

Here is what we have in the “PlayerControls.cs” script.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
    public BaseControls baseControls;
    public Vector2 movementInputs;
    public float rotation;
    public float walkSpeed = 1f, runSpeed = 5f, rotationSpeed = 500f;
    public float gravity = 8f;
    public bool run = true;
    CharacterController controller;
    public Rigidbody rb;
    [SerializeField] GameObject player;
    MouseMovementControls mouseMovementControls;
    Vector3 velocity;
    void Awake()
    {
        mouseMovementControls = player.GetComponent<MouseMovementControls>();
    }
    void Start()
    {
        controller = GetComponent<CharacterController>();
        rb = GetComponent<Rigidbody>();
    }
    void Update()
    {
        GetInputs();
        Locomotion();
    }
    public void Locomotion()
    {
        if (mouseMovementControls.leftAndRightMouseButtons)//mouse
        {
            movementInputs.y = 1;
        }
        //Rotating
        Vector3 characterRotation = transform.eulerAngles + new Vector3(0, rotation * rotationSpeed, 0) * Time.deltaTime;
        transform.eulerAngles = characterRotation;
        //walking and running
        float speed = walkSpeed;
        if (run)
        {
             speed *= runSpeed;
             if (movementInputs.y < 0)
             {
                 speed = walkSpeed;
             }
        }
        velocity = speed * Time.deltaTime * (transform.forward * movementInputs.y + transform.right * movementInputs.x);
        velocity.y -= gravity * Time.deltaTime;
        controller.Move(velocity);
    }
        void GetInputs()
    {
        if (Input.GetKeyDown(baseControls.runWalk))
        {
            run = !run;
        }
        if (Input.GetKey(baseControls.forward)) 
        {
            movementInputs.y = 1; 
        }
        if (Input.GetKey(baseControls.backward)) 
        {
            if (Input.GetKey(baseControls.forward)) 
            {
                movementInputs.y = 0; 
            }
            else
            {
                movementInputs.y = -1; 
            }
        }
        if ((!Input.GetKey(baseControls.forward)) && !Input.GetKey(baseControls.backward))
        {
            movementInputs.y = 0;
        }
        if (Input.GetKey(baseControls.strafeRight))
        {
            movementInputs.x = 1;
        }
        if (Input.GetKey(baseControls.strafeLeft))
        {
            if (Input.GetKey(baseControls.strafeRight))
            {
                movementInputs.x = 0;
            }
            else
            {
                movementInputs.x = -1;
            }
        }
        if ((!Input.GetKey(baseControls.strafeRight)) && !Input.GetKey(baseControls.strafeLeft))
        {
            movementInputs.x = 0;
        }
        if (Input.GetKey(baseControls.rotateRight))
        {
            rotation = 1;
        }
        if (Input.GetKey(baseControls.rotateLeft))
        {
            if (Input.GetKey(baseControls.rotateRight))
            {
                rotation = 0;
            }
            else
            {
                rotation = -1;
            }   
        }
        if ((!Input.GetKey(baseControls.rotateLeft)) && !Input.GetKey(baseControls.rotateRight))
        {
            rotation = 0;
        }
    }
}

Congratz on finishing another Tutorial: Unity Rotate Object – Mouse Movement! The next tutorial will add some basic animations to the player character!

Until next time, May The Force Be With You, Always. – Dragon

Tagged

1 thought on “Unity Rotate Object With Mouse: FREE Tutorial #5 Multiplayer MMO Game

  1. Абсолютно стильные новинки моды.
    Важные новости известнейших подуимов.
    Модные дома, бренды, гедонизм.
    Интересное место для трендовых людей.
    https://outstreet.ru/

Leave a Reply

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