Hi everyone, I have a problem with raycasts and I would like to understand why it doesn’t work.
I’m using raycasts to check if there is ground under the player’s feet to see if I can place an object under it, it seems like once in 10 times the raycast returns false and I don’t know why.
Like the picture shows the raycast should be returning true cause it should hit the object under him (the red line is a gizmo that shows the raycast direction with the starting point at the top and the endpoint below).
It seems like if I move the character (like if I just make a simple rotation) the raycast is finally able to return true, it makes no sense.
Can someone help me with this?
Let me explain the code, I have made a method that is called in the update method, it checks if the player pressed the jump button and every 0.1s set a boolean called has to place to true.
In my Fixed Update if the has to place boolean is set to true then I make a raycast to the ground to check if I can place the block under the player feet like this and change the position of the player and the block like this :
RaycastHit hit;
//ray to the ground with the height of the block
Ray ray = new Ray(transform.position, -transform.up * (0.8f + 1));
//if the raycast hit and the hastoplace true and block available then :
if (Physics.Raycast(transform.position, transform.TransformVector(Vector3.down), out hit, (0.8f + 1)) && hasToPlace&& manager.CheckAvailable())
{
//place the player and the block at the right place
JumpPlacement(hit.point);
//reset hastoplace
hasToPlace = false;
//if the button is not pressed or the block not available then make a jump
if (!manager.IsJumpPressed || !manager.CheckAvailable())
{
//method to jump
Jump(1.5f);
}
}
The method JumpPlacement as I said earlier place the player and the block at the right place like this :
public void JumpPlacement(Vector3 pos)
{
//return the neaarest block
GameObject nearest = ReturnNearest(herd);
//add the block to the list stack to not call it again
blockStack.Add(nearest.transform);
//disable player character controller
manager.Controller.enabled = false;
//place the player a little upper than the block height
transform.position = new Vector3(pos.x, pos.y + blockHeight + 1, pos.z);
//place the block at the hit.point (y axis a little bit upper cause the pivot of the block is at the center of it
nearest.transform.position = pos + new Vector3(0, 0.4f, 0);
}
And then if the player keeps the button pressed, it loops again.