3D Real-Time-Strategy (RTS) Game Tutorial – Part 2 (C#)
We started to create and place buildings in Part 1. In this part, we will move our camera with mouse. As you know, usually camera moves when the cursor touches to edge of screen. Also, holding right mouse button down provides camera movement when you drag the mouse. Both of them are popular movements.
Firstly, lets move the camera with mouse button and drag. We need a float speed variable and x&y positions of the mouse.
Create a new C# script and attach it to the camera.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
float speed = 10.0f; void Update () { if (Input.GetMouseButton (1)) { if (Input.GetAxis ("Mouse X") > 0) { transform.position += new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } else if (Input.GetAxis ("Mouse X") < 0) { transform.position += new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } } } |
When you hold right mouse button down and drag it, camera moves. You don’t need to do this for “Mouse Y”, it works.
The other solution is to drag the cursor to the edges of screen. We need speed, boundary, width and height.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
float speed = 10.0f; int boundary = 1; int width; int height; void Start () { width = Screen.width; height = Screen.height; } void Update () { if (Input.mousePosition.x > width - boundary) { transform.position -= new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, 0.0f); } if (Input.mousePosition.x < 0 + boundary) { transform.position -= new Vector3 (Input.GetAxisRaw ("Mouse X") * Time.deltaTime * speed, 0.0f, 0.0f); } if (Input.mousePosition.y > height - boundary) { transform.position -= new Vector3 (0.0f, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } if (Input.mousePosition.y < 0 + boundary) { transform.position -= new Vector3 (0.0f, 0.0f, Input.GetAxisRaw ("Mouse Y") * Time.deltaTime * speed); } } |
Use whichever you want, both of them are so cool.
©Coffee Break Codes – 3D Real-Time-Strategy (RTS) Game Tutorial – Unity3D
Following this tutorial, So far so good 🙂 but when is the next part being added?
Were is part 3?