Wednesday, November 6, 2019

Player Controllable Physics Ball

Just two scripts for now without proper explanation, but they should work as long as you have a sphere with sphere collider and rigidbody, add those scripts to it and point first one's head property to your camera :3
using UnityEngine;
 
public class BallPlayerController : MonoBehaviour
{
 public Transform head;
 
 public float movementTorque = 6.0F;
 
 private Rigidbody rb;
 
 private float pitch;
 private float yaw;
 
 // Use this for initialization
 void Start()
 {
  rb = GetComponent<Rigidbody>();
  head.parent = null;
 }
 
 // Update physics
 void FixedUpdate()
 {
  //Add torque to rotate ball in the direction we are looking
  rb.AddTorque(-head.forward * Input.GetAxis("Horizontal"* movementTorque);
  rb.AddTorque(head.right * Input.GetAxis("Vertical"* movementTorque);
 }
 
 // Update is called once per frame
 void Update()
 {
  //Rotate head around and make it follow the player
  yaw += Input.GetAxis("Mouse X") * 10;
  pitch = Mathf.Clamp(pitch - Input.GetAxis("Mouse Y") * 5, -70, 70);
  head.rotation = Quaternion.Euler(pitch, yaw, 0);
  head.transform.position = transform.position - head.forward * 5 + Vector3.up * 1;
 }
}
using UnityEngine;
 
public class PhysicsJump : MonoBehaviour
{
 public float jumpForce = 5;
 
 public bool grounded;
 
 private bool jump = false;
 
 private Rigidbody rb;
 
 void Start()
 {
  rb = GetComponent<Rigidbody>();
 }
 
 private void Update()
 {
  jump = Input.GetButtonDown("Jump");
 }
 
 void FixedUpdate()
 {
  if (rb.IsSleeping())
   grounded = true;
 
  if (grounded)
  {
   if (jump)
   {
    rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
   }
  }
  jump = false;
  grounded = false;
 }
 
 private void OnCollisionStay(Collision collision)
 {
  for (int i = 0; i < collision.contactCount; i++)
  {
   var cp = collision.GetContact(i);
   if (cp.normal.y > 0)
   {
    grounded = true;
   }
  }
 }
}

No comments:

Post a Comment