Until now I've been developing my player character using a Character Controller, but have since decided to switch to rigidbody due to the controller's limitations. In order for my movement code to run as expected I need to know when the player is colliding with anything, and the normal of the surface it's colliding with. This is easy with a Character Controller, but is there a simple way to do it with a rigidbody?
Here is a stripped down version of the script I'm using for collisions.
// Used in other scripts (Necessary)
public GameObject ground = null;
public Vector3 groundNormal;
public bool onGround;
// Used internally
public bool isColliding;
public float slopeLimit;
// Character Controller
public CharacterController controller;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
// Check if the player is colliding with anything (Character Controller)
if (controller.collisionFlags == CollisionFlags.None)
{
isColliding = false;
}
else
{
isColliding = true;
}
// Check if the player is standing on the ground
if (isColliding && groundNormal != Vector3.zero)
{
onGround = true;
}
else
{
onGround = false;
}
}
void OnControllerColliderHit(ControllerColliderHit hit)
{
// Check for floor
if (Vector3.Angle(transform.up, hit.normal) <= slopeLimit)
{
// Store floor object data
ground = hit.gameObject;
// Store ground surface normal
groundNormal = Vector3.Normalize(hit.normal);
}
else
{
// reset variables
ground = null;
groundNormal = Vector3.zero;
}
}
slopeLimit
is a static value. Additionally, getting the ground object isn't actually necessary atm, but I plan on using it later.
Edit:
Currently I'm using controller.collisionFlags
to detect when the player is colliding with something and haven't been able to find a similar alternative. Setting the isColliding
bool to true using Rigidbody.OnCollisionStay
would be simple, but setting it to false without use of another void function seems difficult. is that possible at all?
collision.contacts[0].normal
, no? Want to edit your question to describe the bool problem in more detail? \$\endgroup\$collision.contacts
produces garbage data so I avoided using it, but I couldn't figure out the syntax for the linked alternative,ContactPoint.normal
. I'll try it though. As for the bool problem, yeah I'll do that. \$\endgroup\$collision.GetContact(0).normal
to avoid allocation, if that's what you're talking about. \$\endgroup\$