- Home /
Why my function not working with less than velocity?,why my function not work with an If statements with a greater/less than
im making an OnCollisionEnter function. the code is should be like this, the function is called if the player touch the finish line with less than 0.5f velocity. the point is, i want to make the scene restarted when the player is not moving or have a 0 velocity. the problem is sometimes its working but sometimes its doesn't work. sorry im new in unity and my english so bad. i hope someone can help me
public void OnCollisionEnter (Collision collisionInfo)
{
if (collisionInfo.collider.name == "FinishLine")
{
float Speed = rb.velocity.magnitude;
if (Speed <= 0.5f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
Answer by Rachmanichou · Mar 22 at 09:34 AM
Hi,
If I get it correct, you're trying to get your scene to restart when your player is not or almost not moving. If it is such, why not simply have something like this:
public Rigidbody playerRB ;
void Start()
{
playerRB = GetComponent<Rigidbody>() ;
}
void FixedUpdate()
{
if (playerRB.velocity.magnitude <= .5f)
{
Application.LoadScene(Application.nameOfYourScene) ;
}
}
As for your code, I am not really sure of what I am going to say, but I think that a mild mistake could be found in your instantiation of the floating variable Speed. By the time you get your rigidbody's speed, it could be that it has already changed. So maybe that you simply could use your collision's embedded variables:
void OnCollisionEnter(Collision collisionInfo)
{
if (collision.relativeVelocity.magnitude >= .5f)
Application.LoadLevel(Application.nameofYourScene) ;
}
Aside from that, the use of the OnCollisionEnter() void is quite scenery-dependent. So for example, if you've placed your collider a bit too high or a bit too low, or anything, this void won't be called.
Hope that helps.
Your answer
Follow this Question
Related Questions
WaitForSeconds twice in 1 if statement, not working 2 Answers
Collider question 0 Answers
Rigidbody magnitude comparison is not working correctlly? 2 Answers
only updating number vars once 1 Answer