Last active
April 9, 2021 17:30
-
-
Save adamtuliper/fbed2bdf658deb158815d621d82f9949 to your computer and use it in GitHub Desktop.
Ground detection, mouse look, and jump
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class PlayerControllerWithPhysics : MonoBehaviour | |
{ | |
private Rigidbody rb; | |
private float horizontal; | |
private float vertical; | |
public float Speed = 5; | |
private float colliderSize; | |
private bool jump; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
rb = GetComponent<Rigidbody>(); | |
colliderSize = GetComponent<BoxCollider>().bounds.extents.y; | |
Debug.Log(colliderSize); | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
//Read input | |
horizontal = Input.GetAxis("Horizontal"); | |
vertical = Input.GetAxis("Vertical"); | |
if (Input.GetButtonDown("Jump")) | |
{ | |
jump = true; | |
} | |
} | |
void FixedUpdate() | |
{ | |
//Move an object with physics | |
//rb.velocity = new Vector3(1 * horizontal, rb.velocity.y, 1 * vertical); | |
//No speed, no gravity (almost no gravity) | |
//rb.velocity = transform.TransformDirection(horizontal, 0, vertical) | |
//With speed, y gravity is overridden to be almost 0 | |
//rb.velocity = transform.TransformDirection(horizontal, 0, vertical) * Speed; | |
//With speed and gravity in the y axis (ie normal gravity) | |
rb.velocity = transform.TransformDirection(horizontal, 0, vertical) * Speed + (new Vector3(0, rb.velocity.y, 0)); | |
if (jump && IsGrounded()) | |
{ | |
rb.AddForce(0, 4, 0, ForceMode.Impulse); | |
jump = false; | |
} | |
var rotationSpeed = 6f; | |
//Method 1 | |
// based off of horizontal | |
//var euler = transform.localEulerAngles; | |
//euler.y += horizontal * rotationSpeed; | |
//rb.rotation = Quaternion.Euler(euler); | |
//Method 2 | |
//based off of mouse look | |
rb.rotation = Quaternion.Euler(rb.rotation.eulerAngles + new Vector3(0f, rotationSpeed * Input.GetAxis("Mouse X"), 0f)); | |
} | |
bool IsGrounded() | |
{ | |
return Physics.Raycast(transform.position, Vector3.down, colliderSize + 0.1f); | |
} | |
private void OnTriggerEnter(Collider other) | |
{ | |
//Destroy(other.gameObject); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment