Whenever the player picks up an object underneath him, it causes weird behaviour. So I'm trying to prevent the picking-up whenever the pickable object is under the player. All pickable objects are in a different layer than the player. Here is what I have tried:
if (PickingUp)
{
if (currentlyPickedUpObject == null)
{
if (lookObject != null)
{
if (Physics.Raycast(transform.position, Vector3.down, out hit))
{
if (hit.collider.gameObject == player.gameObject)
{
// object is under player
Debug.Log("can't pick up");
}
}
else
{
PickUpObject();
}
}
}
}
But this disabled the entire picking up, now I can't pick up objects whether they are under the player or not.
How can I fix this to achieve what I want?
CodePudding user response:
I assume this is a player script. Since raycast origins at transform.position, I guess the origin is inside the player. There's a good chance ray is being cast and ends immediately always hitting player.
I'm failing to see how searching for player would help, I think what you need is raycasting in search for an object.
Also, as mentioned in the comment, the else statement is in the wrong place, and the solution 1) I provided will fail.
Possible solutions:
in the inner if statement check if you hit the pickable object not the player. I'm assuming there's more than one object, so you can use tags to determine which objects are pickable, anything that works for you. Then, you know, you stand on an object. You might need to ignore player's layer during raycasting.
Create a trigger at the bottom of the player. If pickable object collides with it, you are standing on it.
Fix the issues with weird behaviour. After all, I guess player should be able to always pick up and item, and being unable to do so would be frustrating.
CodePudding user response:
well change the position of the else
.. currently as soon as anything at all (e.g. the ground) is below you do not call PickUpObject
.
I also guess you would rather want to check for
hit.collider.gameObject == lookObject
not player.gameObject
if (PickingUp)
{
if (currentlyPickedUpObject == null)
{
if (lookObject != null)
{
if (Physics.Raycast(transform.position, Vector3.down, out hit) && hit.collider.gameObject == lookObject)
{
// object is under player
Debug.Log("can't pick up");
}
else
{
PickUpObject();
}
}
}
}
Since you already seem to know the object you are going to pickup anyway you could also simply define a certain angle range it may not fall in. That might be easier than a Raycast:
float THRESHOLD = 5f;
if (PickingUp)
{
if (currentlyPickedUpObject == null)
{
if (lookObject != null)
{
if(Vector3.Angle(Vector3.down, lookObject.transform.position - transform.position) <= THRESHOLD)
{
PickUpObject();
}
}
}
}