Game Development Community

Move one object towards another object?

by amaranthia · in Torque Game Builder · 09/26/2006 (7:59 pm) · 3 replies

I have a feeling this is really simple, but I'm getting stuck...

I have two objects in a scene. A chicken and a monster. I need the monster to move towards the chicken. The chicken is constantly moving. The ID for the chicken in the Object Tree is 2119. I tried setting %chicken to this, and it did grab the initial information about the chicken, but only the initial info. When I plugged it into the code below (constantly looping), the monster moved to the initial position of the chicken, but that was it. I think I'm referencing the wrong ID for the chicken, but I'm not sure how to get the right one.

Note: when I track %chicken, none of the values for the object update. however, when I track %this, the values update as hoped. I noticed that an ID is auto generated for %this (monster) that doesn't match the ID for the monster in the object tree. I also noticed that the ID for the monstser (%this) changes each time I test the level. Looks like it's auto generated, and I'm not sure how to capture something like this...

Any idea what I'm doing wrong? Here's my code snippet:

//this loops over and over
function Sprite::moveSprite(%this)
{
  
        //get chicken's position
        %chicken = 2119;
        %chicken.currentX = %chicken.getPositionX();        
        %chicken.currentY = %chicken.getPositionY(); 


       //get monster's position
        %this.currentX = %this.getPositionX();
        %this.currentY = %this.getPositionY();


       //move monster toward chicken
        %this.moveTo(%chicken.currentX, %chicken.currentY, %this.speed);
}

#1
09/26/2006 (8:36 pm)
Well, the first thing that would make this easier is using named objects. In the Edit Tab, scripting panel, you can choose a Name for an object (like "chicken") and can use that anywhere in script to access the chicken. The name in script will be equivalent to whatever the object's ID is.

I was going to have a second thing to say, but then I realized that this is probably your problem. :)

Another way to get the ID of the chicken is to set it's class to something like "Chicken" and then (like you did with Sprite::moveSprite), make a function like this:
function Chicken::onLevelLoaded(%this, %scenegraph)
{
     $chicken = %this;
}

That would make a global variable that holds the chicken's ID when the level is started.

I think this stuff is covered in-depth in the Fish Game tutorial.
Hope that helps!
#2
09/26/2006 (9:00 pm)
It worked! Thank you!!
#3
09/26/2006 (10:24 pm)
No problem. I remember the small things that got me stuck for hours when I was still learning. Oh wait, I ran into one today ;)