Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using UnityEngine;
public class Movement : MonoBehaviour
{
[SerializeField]
private float movementSpeed;
[SerializeField]
private float jumpPower;
private bool grounded;
private float groundCheckDistance = 1;
private float boxColliderHeight = .1f;
private float sizeDivisor = 1.1f;
private Vector3 size;
private BoxCollider boxCollider;
private new Rigidbody rigidbody;
void Start()
{
boxCollider = GetComponent<BoxCollider>();
rigidbody = GetComponent<Rigidbody>();
size = new Vector3(boxCollider.size.x / sizeDivisor, boxColliderHeight, boxCollider.size.z / sizeDivisor);
}
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 velocity = new Vector3(h, 0, v);
velocity = transform.TransformDirection(velocity);
velocity *= movementSpeed;
velocity -= rigidbody.velocity;
rigidbody.AddForce(velocity);
var center = transform.TransformPoint(boxCollider.center);
grounded = Physics.BoxCast(center, size, Vector3.down, transform.rotation, groundCheckDistance);
if (Input.GetButtonDown("Jump") && grounded)
{
rigidbody.AddForce(Vector3.up * jumpPower);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.