x


Need help with Raycasting

I don't know what I'm doing wrong, so hopefully someone will want to give some quick advice.

The player object is controlled by the keyboard (WASD, Enter/Return), and it activates objects around him when the player presses Enter. I don't want the object to activate unless the player is facing the object, so I tried to use Raycasting from the player to the collider object (now simply a cube) that surrounds the object:

//Get the ray coming from Player
public bool IsFacingObject()
{
    return (Physics.Raycast(transform.position, transform.forward, 10));
}

The above method returns true if the ray coming from the player hits something, false if it doesn't.

Now for the Box collider:

void Update()
{
    if (canTalk && Input.GetButtonDown("Enter") && player.GetComponent<LukaCController>().IsFacingObject())
    {
        if (GetComponent<MessageBoxScript>())
        {
            Destroy(GetComponent<MessageBoxScript>());
        }else
        {
            begin = gameObject.AddComponent<MessageBoxScript>();
            begin.MessageBox(font1, font2, faceGraphic,
                0, "Convo Box", true, "Hi, I'm the Convo Box!$ How are you?");
        }
    }

}

canTalk is a boolean that returns true if the player's collider hits the trigger that surrounds the cube. player.GetComponent().IsFacingObject() is the method I showed you above, returning true or false.

However, player.GetComponent().IsFacingObject() doesn't return true, even though the player is facing the cube and is even touching the cube. Why isn't the raycast seeing the cube?

more ▼

asked Jun 11 '10 at 01:44 AM

cyangamer gravatar image

cyangamer
29 2 2 6

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Start by using Debug.DrawRay on IsFacingObject to ensure that the raycast would actually be hitting something. Without seeing the scene, it's possible that your object's pivot (transform.position) is higher than the top of the cube, and that your ray is overshooting it.

more ▼

answered Jun 11 '10 at 07:06 AM

Ricardo gravatar image

Ricardo
5.2k 20 32 96

That was basically it. The ray was undershooting the cube and missing the mark. It is fixed now. Thanks!

Jun 12 '10 at 05:03 AM cyangamer
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1878
x1532
x675
x81

asked: Jun 11 '10 at 01:44 AM

Seen: 1258 times

Last Updated: Jun 11 '10 at 01:44 AM