c# movement code example
Example 1: movement script c#
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour
{
CharacterController characterController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
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 move character
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float speed = 5.0f;
private void Update()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
transform.Translate(new Vector3(horizontal, 0, vertical) * (speed * Time.deltaTime));
}
}
Example 3: movement script c#
private float speed = 2.0f;
public GameObject character;
void Update () {
if (Input.GetKey(KeyCode.RightArrow)){
transform.position += Vector3.right * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.LeftArrow)){
transform.position += Vector3.left * speed * Time.deltaTime;
}
if (Input.GetKey(KeyCode.UpArrow)){
transform.position += Vector3.up*speed* Time.deltaTime;
}forward;
if (Input.GetKey(KeyCode.DownArrow)){
transform.position += Vector3.down *speed * Time.deltaTime;
}
}
Example 4: C# movement
Rigidbody2D body;
float horizontal;
float vertical;
float moveLimiter = 0.7f;
public float runSpeed = 20.0f;
void Start ()
{
body = GetComponent<Rigidbody2D>();
}
void Update()
{
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
}
void FixedUpdate()
{
if (horizontal != 0 && vertical != 0)
{
horizontal *= moveLimiter;
vertical *= moveLimiter;
}
body.velocity = new Vector2(horizontal * runSpeed, vertical * runSpeed);
}