View Full Version : Quick method question
substance
June 10th, 2008, 03:22 PM
I made a method for applying force to x and y velocities of an object:
public function applyForce(_xForce:Number = null,_yForce:Number = null):void
{
if (_xForce)
{
velocity.x *= _xForce;
}
if (_yForce)
{
velocity.y *= _yForce;
}
}
So if I wanted to only apply xForce I would do a call like :
applyForce(xForce);
But what if i only wanted to apply yForce? I tried:
applyForce(,yForce);
//or
applyForce(null,yForce);
Dom_
June 10th, 2008, 03:36 PM
why not abstract them into two methods ?
substance
June 10th, 2008, 05:18 PM
Well it's more of a hypothetical question if anything. I'm just wondering if it is possible.
Iamthejuggler
June 10th, 2008, 05:28 PM
No, you have to specify the variables up to and including the one you actually want to specify even when giving them defaults in the constructor. It's kinda annoying.
Krilnon
June 10th, 2008, 05:59 PM
It's possible… if you don't mind passing a cardinal value of some sort as the first argument:
public function applyForce(_xForce:Number = NaN,_yForce:Number = NaN):void
{
if(!isNaN(_xForce))
{
velocity.x *= _xForce;
}
if (!isNaN(_yForce))
{
velocity.y *= _yForce;
}
}
You could also just pass 1, since that would be a more logical value (and you could check for it, too). null usually refers to an Object reference of some sort, and while Numbers are Objects, they are also primitives so you can't really have a null primitive reference.
Fidodo
June 10th, 2008, 06:57 PM
Well for this particular example I'd say apply both forces every time, but default the value to 1, since x*1=x
But you're asking about how to do this in general cases?
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.