- Home /
How can you make a mouse pan in game?
I have been following a tutorial online about how to make an rts strategy game. In my scene, there are 3 object; A terrain called TerrainMain, the main camera, and a cube called target. Here is the code of my non-functioning c# script.
using UnityEngine;
using System.Collections;
public class MousePoint : MonoBehaviour {
RaycastHit hit;
private float raycastLength = 400;
void Update()
{
GameObject Target = GameObject.Find ("Target");
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if(Physics.Raycast (ray, out hit, raycastLength)){
Debug.Log (hit.collider.name);
if (hit.collider.name == "TerrainMain")
{
Target.transform.position = hit.point;
}
}
Debug.DrawRay(ray.origin, ray.direction*raycastLength, Color.yellow);
}
}
I can get the cube to move around the terrain with my mouse, but I can't actually pan in the x and z directions.
Do you mean you want the camera to pan around according to the mouses position or that you want the mouse to move around on the screen?
Yeah, sorry I mistyped it. I want the camera to move to the left when the mouse was at the left of the screen, the right when the mouse was at the right (etc.)
Answer by blueteak · Dec 31, 2013 at 06:14 PM
You need a fair bit more code to get the camera to pan:
First - You want a if(Input.GetMouseButton(0))
to trigger the panning if LMB is pressed. This will go under the if(hit.collider.name == "TerrainMain")
Second - Once you have checked that you are clicking on the terrain, you need to move the camera when you move the mouse while clicked.
I'm not sure the best way to do this, but I would try
transform.Translate(new Vector3( Input.GetAxis("Mouse X"), 0 , Input.GetAxis("Mouse Y")));
within that last if( button pressed ). (This assumes that the script is attached to the camera, otherwise use Camera.main.transform.Translate(...);
Your answer
![](https://koobas.hobune.stream/wayback/20220613125228im_/https://answers.unity.com/themes/thub/images/avi.jpg)