Create a new C# script and add following code in it and then attach it to camera object in scene and then you can use WASD keys for moving camera.
Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public float speed = 10.0f;
void Update()
{
// for getting input from WASD keys
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// for moving camera based on input
transform.position += new Vector3(horizontal, 0, vertical) * speed * Time.deltaTime;
}
}
We uses Input.GetAxis() method for getting horizontal and vertical input from WASD keys and then we update camera position according to input. We can change its speed variable for how much fast or slow we want to move our camera.
We can also use Input.GetKey() method for particular key input instead of raw axis input. Here is an example for this:
Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public float speed = 10.0f;
public KeyCode forwardKey = KeyCode.W;
public KeyCode backwardKey = KeyCode.S;
public KeyCode leftKey = KeyCode.A;
public KeyCode rightKey = KeyCode.D;
void Update()
{
// for moving camera forward
if (Input.GetKey(forwardKey))
{
transform.position += transform.forward * speed * Time.deltaTime;
}
// for moving camera backward
if (Input.GetKey(backwardKey))
{
transform.position -= transform.forward * speed * Time.deltaTime;
}
// for moving camera left
if (Input.GetKey(leftKey))
{
transform.position -= transform.right * speed * Time.deltaTime;
}
// for moving camera right
if (Input.GetKey(rightKey))
{
transform.position += transform.right * speed * Time.deltaTime;
}
}
}
In this script we can assign any key to forwardKey, backwardKey, leftKey, and rightKey variables inspector window to move our camera.
We can also use Cinemachine for creating virtual camera and there are many other ways of doing this.
Comments
Post a Comment