Skip to content

Instantly share code, notes, and snippets.

@happyharis
Last active April 9, 2018 04:14
Show Gist options
  • Save happyharis/3ddfce9732f5c07b0760cd75bd13bab4 to your computer and use it in GitHub Desktop.
Save happyharis/3ddfce9732f5c07b0760cd75bd13bab4 to your computer and use it in GitHub Desktop.
Player Motor and Controller part 1
// PlayerController.cs
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour {
[SerializeField] //will show up on the inspector, however, still having the protection as a private variable
private float speed = 5f;
[SerializeField]
private float lookSensitivity = 3f;
private PlayerMotor motor;
void Start () {
motor = GetComponent<PlayerMotor> ();
}
void Update () {
// Calculate movement velocity as 3D vector
float _xMov = Input.GetAxisRaw ("Horizontal");
float _zMov = Input.GetAxisRaw ("Vertical");
// Move horizontally (1, 0, 0)
Vector3 _movHorizontal = transform.right * _xMov;
// Move vertically (0, 0, 1)
Vector3 _movVertical = transform.forward * _zMov;
// Final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
// Apply movement
motor.Move(_velocity);
}
}
// PlayerMotor.cs
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour {
private Vector3 velocity = Vector3.zero;
[SerializeField]
private Camera cam;
private Rigidbody rb;
// Gets a movement vector
public void Move(Vector3 _velocity){
velocity = _velocity;
}
// Run every physics iteration
void FixedUpdate (){
PerformMovement ();
}
// Perform movement based on velocity variable
void PerformMovement() {
if (velocity != Vector3.zero)
{
rb.MovePosition (rb.position + velocity * Time.fixedDeltaTime);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment