basic movement c# 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: 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);
}