- Home /
Raycast check not returning false
I am attempting to create a hovering player by using a raycast that exerts an upwards force if said player is less than a certain distance away from the ground. The problem is, the raycast is always detecting the ground being within that certain distance, even if the player is much too far away. The result is that my player just keeps floating up.
private RaycastHit hitInfo;
void RayCheck () { //fires Raycast down
Physics.Raycast(transform.position, Vector3.down, out hitInfo, 2f);
Debug.DrawRay (transform.position, Vector3.down * 2f);
if (hitInfo.distance < 2) {
rb.AddForce (Vector3.up * hoverForce);
}
}
The script thinks that hitinfo.distance is always less than 2, even when it clearly isn't. Does anyone have an idea of why this is happening? Or if the idea just fundamentally won't work?
Have you tried putting the Physics.Raycast in an if and only running the logic if it actually hits something? Such as:
void FixedUpdate()
{
RaycastHit hitInfo;
if (Physics.Raycast(transform.position, Vector3.down, out hitInfo, 2.0f))
{
if(hitInfo.distance < 2)
{
rb.AddForce(Vector3.up * hoverForce);
}
}
}
Thank you! It appeared that this was the problem.
Answer by CaffeineAndCoffee · Feb 28, 2017 at 10:18 PM
In this case, the raycast should be inside of an if loop,
RaycastHit hitInfo;
void RayCheck () {
if (Physics.Raycast (transform.position, Vector3.down, out hitInfo, 2f)) {
rb.AddForce (Vector3.up * hoverForce);
}
}
You may have to play around with the Rigidbody settings and the hoverforce float to get the desired effect.
Thanks! I will need to tinker with it so I'm not bobbling up and down, but this does appear to be what the doctor ordered!
Answer by jwulf · Feb 28, 2017 at 10:16 PM
I could imagine, the Raycast hits the player-object itself?
As a fourth parameter for Raycast, you can assign a LayerMask (https://docs.unity3d.com/ScriptReference/Physics.Raycast.html) of layers to ignore. Set your player's layer (which is, I assume, different from the Ground Layer) there and if this was indeed the problem, it should'nt happen again.
Your answer
Follow this Question
Related Questions
Raycast won't hit Collider 1 Answer
Not getting right value; ScreenPointToRay 0 Answers
help the build button in the build settings is grayed out 0 Answers
Raycast not registering hits when mouse is moving fast. 2 Answers
How to make my raycast also hit deactive objects WITHOUT showing the object? 1 Answer