Game Development Community

Help appreciated with custom object and variable scope

by Norman Potter · in General Discussion · 04/12/2007 (6:00 am) · 2 replies

Sooooo!

What I decided to do was take the key binding example in a few of the tutorials and create a ControlHandler class.

My problem is that what I've managed so far isn't very elegant code-wise (code below). I don't want the state of the keys pressed held in global variables.

I can't for the life of me get %this to work and hold them in the context of the object.

Any help greatly appreciated, guys and gals.

function createControlHandler()
{
	$controlHandler = new ScriptObject() { class = ControlHandler; };
}

function ControlHandler::onAdd(%this)
{
	$keyUpPressed = false;
	$keyDownPressed = false;
	$keyRightPressed = false;
	$keyLeftPressed = false;
}

function ControlHandler::bindControls(%this)
{
	moveMap.bindCmd(keyboard, "w", "keyPress(up);", "keyPress(upstop);");
	moveMap.bindCmd(keyboard, "s", "keyPress(down);", "keyPress(downstop);");
	moveMap.bindCmd(keyboard, "d", "keyPress(right);", "keyPress(rightstop);");
	moveMap.bindCmd(keyboard, "a", "keyPress(left);", "keyPress(leftstop);");
}

function keyPress(%direction)
{
	switch$(%direction)
	{
	case "up":
		$keyUpPressed = true;
	case "down":
		$keyDownPressed = true;
	case "right":
		$keyRightPressed = true;
	case "left":
		$keyLeftPressed = true;
	case "upstop":
		$keyUpPressed = false;
	case "downstop":
		$keyDownPressed = false;
	case "rightstop":
		$keyRightPressed = false;
	case "leftstop":
		$keyLeftPressed = false;
	}

	updateMovement();
}

function updateMovement()
{
	if($keyUpPressed)
	{
		$Player.setLinearVelocityY(-60);
	}
	
	if($keyDownPressed)
	{
		$Player.setLinearVelocityY(60);
	}
	
	if(!$keyUpPressed && !$keyDownPressed)
	{
		$player.setLinearVelocityY(0);
	}
	
	if($keyRightPressed)
	{
		$player.setLinearVelocityX(60);
	}

	if($keyLeftPressed)
	{
		$player.setLinearVelocityX(-60);
	}
	
	if(!$keyRightPressed && !$keyLeftPressed)
	{
		$player.setLinearVelocityX(0);
	}
}

#1
04/12/2007 (7:05 am)
What is the problem? Is not onAdd () getting called?

Just store whatever like %this.keyUpPressed = false
#2
04/12/2007 (7:12 am)
Sorry, I don't think I made the problem clear enough.

I know keyPress() gets called and it know it filters down to updateMovement().

If I try and set %this.keyUpPressed in keyPress() it doesn't get set and so updateMovement() doesn't know what's going on.

I've looked at a couple of other custom classes and followed the same pattern. What you're suggesting should work but for some reason, it doesn't :-(