2

I have a function called collisioncheck. Right now it works perfectly by checking variables that apply to a player, such as playerPosX, playerVelX, playermaskIMG, etc.

What I want to do is something like collisioncheck(object), so that say I call collisioncheck(player) it will check the variables like above with playerPosX etc. and if I call collisioncheck(zombie) then it will instead check zombiePosX, etc.

How could I do this?

If you have any questions please ask as I am not really very good at explaining this... thanks in advance!

1
  • Is there a particular reason in your case not to give the fields the same name in each type? e.g. Just have posX, velX, maskIMG, regardless of whether it is a player, zombie or something else? Commented Oct 22, 2011 at 5:03

3 Answers 3

3

I would strongly suggest that you refactor the code so that variables like

playerPosX
playerPosY
playerVelX
playerVelY
zombiePosX
zombiePosY
zombieVelX
zombieVelY

do not appear in your code. Instead zombie and player should be objects with properties such as velX, velY, posX and posY.

Then collisionCheck can look like

function collisionCheck(object) {
    .... object.posX ...
}

The current object would be compared against all of the other nearby players and zombies by checking each of the properties of these objects.

You really do not want to go the route of dealing with variable names as strings. In essence, properties do this for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes this exactly what I'm looking for! how do I create an object with properties? like what would the syntax for a player object?
Vlad's answer shows how to create an object with properties. In order to update such an object you would write code such as zombie.posX = 4;.
1

Its pretty simple:

function collisioncheck(obj) {
  var posX = obj.posX;
  var velX = obj.velX;
  var maskIMG = obj.maskIMG;
}

// ...

var objectToCheck = {
  'posX' : playerPosX,
  'velX' : playerVelX,
  'maskIMG' : playermaskIMG
};

collisioncheck(objectToCheck);

Comments

0

Here is an example for you

   zombie = { 'posX' : 7,  'posY' : 95 };
   player = { 'posX' : 3,  'posY' : 95 };
   document.write(  zombie.posX );


    function CollisionCheck ( o1 , o2 )
    {

        if ( Math.abs(o1.posX - o2.posX) < 5 )
            {
                document.write ( 'Kaboom!!!' );              
            }        
    }        
    CollisionCheck ( zombie, player );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.