x


If statment based on a function not working

I'm working in a AI script, and i have made the following function to check if the enemy can see the player.

function CanSeePlayer(){

    var hit : RaycastHit;
    var rayDirection = playerObject.transform.position - transform.position;

    if (Physics.Raycast (Seeker.transform.position, rayDirection, hit)) {

        if (hit.transform.tag == "Player") {
            Debug.Log("Can see player");
            return true;
        }else{
            Debug.Log("Can not see player");
            return false;
        }
    }
}

If i put this code outside of the function and in the script it self, it works fine.

But when i try to access the function like this:

if(!CanSeePlayer){
Debug.Log("I cant see the player")
}

The script dosent work, and the Debug command dosent get run, even though it should.

more ▼

asked Apr 21 '10 at 02:02 PM

Mattivc gravatar image

Mattivc
1.7k 55 60 67

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

3 answers: sort voted first

Should it not be:

function CanSeePlayer():boolean { }

more ▼

answered Apr 21 '10 at 03:37 PM

Silverfell gravatar image

Silverfell
98 1 1 7

hehe - nice JS-Fu :) for some reason I'm reminded of: http://thedailywtf.com/Articles/Classic_WTF_-_What_is_Truth_0x3f_.aspx

Apr 21 '10 at 04:52 PM duck ♦♦
(comments are locked)
10|3000 characters needed characters left

Well I was initially going to say that tou need to access the function like this:

if (!CanSeePlayer()) {

(notice the brackets after the function name), however after testing it, in a quirk of javascript syntax, it seems you don't actually need the () so that's not the answer.

Do none of the debug commands run? (you have 3). Do you get any errors?

Another thing I noticed is that you're building the ray direction as the vector between this object and the player object, however you're then casting it from the "Seeker" position (rather than this object's position). Perhaps you meant to write:

if (Physics.Raycast (transform.position, rayDirection, hit)) {

Since you haven't specified what "Seeker" is, it's difficult to know if that part of the code is correct.

more ▼

answered Apr 21 '10 at 02:34 PM

duck gravatar image

duck ♦♦
40.9k 92 148 415

No, none of my 3 Debug commands gets run.

The seeker is the part of the enemy object and it dosent change anything when i change it to what you posted.

Apr 21 '10 at 03:31 PM Mattivc

Oh, and i forgot to menchian i get no errors.

Apr 21 '10 at 03:32 PM Mattivc
(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:

x477
x108
x75

asked: Apr 21 '10 at 02:02 PM

Seen: 718 times

Last Updated: Apr 21 '10 at 02:02 PM