I’m having an issue with my script where once my character collides with another object that the grounded statement switches to “true” only one frame then goes back to “false” for the rest of the time.
My current script:
var walkAcceleration : float = 500;
var walkAccelAirRatio : float = 0.1;
var walkDeacceleration : float = 0.5;
@HideInInspector
var walkDeaccelerationVolx : float;
@HideInInspector
var walkDeaccelerationVolz : float;
var cameraObject : GameObject;
var maxWalkSpeed : float = 50;
@HideInInspector
var horizontalMovement : Vector2;
var jumpVelocity : float = 250;
@HideInInspector
var grounded : boolean = false;
var maxSlope : float = 60;
@HideInInspector
var hor : float;
@HideInInspector
var ver : float;
@HideInInspector
var collisionObject : GameObject;
internal var animator : Animator;
function Start ()
{
animator = GetComponent(Animator);
}
function Update ()
{
hor = Input.GetAxis("Horizontal");
ver = Input.GetAxis("Vertical");
horizontalMovement = Vector2(rigidbody.velocity.x, rigidbody.velocity.z);
if (horizontalMovement.magnitude > maxWalkSpeed)
{
horizontalMovement = horizontalMovement.normalized;
horizontalMovement *= maxWalkSpeed;
}
rigidbody.velocity.x = horizontalMovement.x;
rigidbody.velocity.z = horizontalMovement.y;
if (grounded)
rigidbody.velocity.x = Mathf.SmoothDamp(rigidbody.velocity.x, 0, walkDeaccelerationVolx, walkDeacceleration);
rigidbody.velocity.z = Mathf.SmoothDamp(rigidbody.velocity.z, 0, walkDeaccelerationVolz, walkDeacceleration);
transform.rotation = Quaternion.Euler(0, cameraObject.GetComponent(MouseLook).currentYRotation, 0);
if (grounded)
rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * Time.deltaTime);
else
rigidbody.AddRelativeForce(Input.GetAxis("Horizontal") * walkAcceleration * walkAccelAirRatio * Time.deltaTime, 0, Input.GetAxis("Vertical") * walkAcceleration * walkAccelAirRatio * Time.deltaTime);
if (Input.GetButtonDown("Jump") && grounded)
rigidbody.AddForce(0, jumpVelocity, 0);
if (grounded)
print("is grounded");
}
function FixedUpdate ()
{
animator.SetFloat("Walking", ver);
}
function OnCollisionStay (collision : Collision)
{
print("called");
for (var contact : ContactPoint in collision.contacts)
{
if (Vector3.Angle(contact.normal, Vector3.up) < maxSlope)
grounded = true;
}
}
function OnCollisionExit ()
{
grounded = false;
}
I tested my code with 2 possible issues:
- The main issue turns out to be that OnCollisionStay is only called one frame.
- I tested whether my rigidbody was sleeping. Turns out it was not doing so at all.
I had an answer in the Answers section that I should change the if statement in function OnCollisionStay to an if else statement. However I don’t know how to convert it to an if else since I don’t know what to put what where once I add an else.