Problems with Physics.Raycast
I’m making a small game that mainly just involves picking up and throwing things. To do so, I’m trying to create a Raycast on the player, so that when he gets close enough to something, it’ll show that he can pickup and throw it.
Here's the code:
#pragma strict
function OnCollisionEnter(col : Collision) {
var fwd: Vector3 = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, fwd, 5) && col.gameObject.tag == "Enemy")
{
print("Put em' in the traaaaaaaaaash");
}
}
The problem is that whenever I go up to the object with the "Enemy" tag, nothing shows up on the console. What am I doing wrong?
It's not exactly clear what kind of behaviour you're trying to achieve, but right now your script works like this: OnCollisionEnter() is called during the frame in which you make contact with the enemy. When this happens you send out a raycast. If that hits the enemy then you print to the console. What this means is that the player will have to be directly facing the object while colliding with it. I was able to get the line to print in the console, but it required some finesse with the controls.
The best way to change the script depends on how you want your pickup mechanic to work. Right now you could summarize it like this: "To pick up an object, look directly at it while walking into it." I would say that's not that intuitive and would suggest some possible alternatives such as:
"To pick up an object, walk into it."
"To pick up an object, look directly at it and click the Left $$anonymous$$ouse Button."
"To pick up an object, walk near it and press the Action $$anonymous$$ey."
There are of course many, many other ways you could do this as well. If you could describe exactly what you want to happen, then it would be easier to suggest some solutions.
I want it so that when you walk up close and look at the game object with the tag "Enemy" for you to be able to then click and be able to pick it up and throw it, but right now, I just want the message to show up on the console. What am I doing wrong?
Since you just want to the player to have to be close to, but not actually touching the object, you don't need to use OnCollisionEnter() or any other collision detection. You only need to check that the raycast can hit the object. Since you're already limiting the length of the ray to 5m, this will effectively make it only possible to interact with the object at close range.
For now, you can probably just throw that raycasting code into Update() for testing purposes, but more ideally you'll want to test for mouse clicks before doing the raycast because you won't want to be raycasting every frame.
Also, @TanselAltinel is right; you can just use transform.forward ins$$anonymous$$d of doing the whole thing with TransformDirection().
Your answer
![](https://koobas.hobune.stream/wayback/20220612073908im_/https://answers.unity.com/themes/thub/images/avi.jpg)