unity c# camera movement script code example
Example 1: C# player movement script unity
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
CharacterController characterController;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
public float speed = 9.0f;
private Vector3 moveDirection = Vector3.zero;
private void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
transform.Translate(new Vector3(horizontal, 0, vertical) * (speed * Time.deltaTime));
if (characterController.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
}
}
Example 2: unity camera movement script
using UnityEngine;
public class CameraController : MonoBehaviour {
private float moveSpeed = 0.5f;
private float scrollSpeed = 10f;
void Update () {
if (Input.GetAxisRaw("Horizontal") != 0 || Input.GetAxisRaw("Vertical") != 0) {
transform.position += moveSpeed * new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
}
if (Input.GetAxis("Mouse ScrollWheel") != 0) {
transform.position += scrollSpeed * new Vector3(0, -Input.GetAxis("Mouse ScrollWheel"), 0);
}
}
}
Example 3: how to code a move camera in unity
void Update()
{
if(Input.GetKey(KeyCode.RightArrow))
{
transform.Translate(new Vector3(speed * Time.deltaTime,0,0));
}
if(Input.GetKey(KeyCode.LeftArrow))
{
transform.Translate(new Vector3(-speed * Time.deltaTime,0,0));
}
if(Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(new Vector3(0,-speed * Time.deltaTime,0));
}
if(Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(new Vector3(0,speed * Time.deltaTime,0));
}
}