Using “Magnitude” to calculate distance between objects…

computerking9979computerking9979 Member Posts: 11
edited August 2023 in Working with GS (PC)

Hi everyone,

I have seen a couple of videos (though kinda old) that show using the magnitude function to calculate the distance between objects. However, I’m not able to follow along because the interface is different (they are on a Mac and I’m on a PC, but it also could be the age of the videos).

So could someone tell me how I use the magnitude function to calculate the distance between 2 or more objects?

Thanks in advance.

P.S. Is magnitude the only/best option to find the distance between 2 objects or is there a behavior for it?

Comments

  • adent42adent42 Key Master, Head Chef, Executive Chef, Member, PRO Posts: 3,155

    I don't have the Windows version available to me ATM but the high level:

    • Let's assume two actors. Source and Target. Source is doing the distance calculation, Target is the actor we want to use to calculate distance.
    • Create two integer game level attributes to store the Target's coordinates. We'll call them targetX, targetY.
    • In Target actor create two Constrain Attribute behaviors. One to constrain game.targetX to self.position.X ; one to constrain game.targetY to self.position.Y
    • Assuming only the Source actor cares about the distance, create a real attribute called 'distanceToTarget' on the Source actor. If it's something the whole game cares about, create this attribute at the game level.
    • In the Source actor create a Constrain Attribute Behavior that set self.distanceToTarget to: magnitude( game.targetX - self.position.X, game.targetY - self.position.Y)
    • For debugging and to see this working, add a Display Attribute behavior on the Source actor and have it display the self.distanceToTarget

    Preview and you should see a distance. If you want the distance to always be positive, then wrap magnitude in an abs function.

    Hope that helps!

  • computerking9979computerking9979 Member Posts: 11

    I think this makes sense.

    I’m making a top down scroller where the enemies won’t start shooting until the player is within a certain range. So each enemy would do this calculation individually.

    So would I put the constrain attribute behavior set to self.distanceToTarget in each enemy?

    Thanks for your help.

  • adent42adent42 Key Master, Head Chef, Executive Chef, Member, PRO Posts: 3,155

    Yes, so each enemy would calculate it's distance to the player and the player would be the "target" in this case.

Sign In or Register to comment.