TGB/MiniTutorials/OneWayCollision
From TDN
| One Way Collision | |
|---|---|
Description: This will demonstrate how to set up one way collision for levels in platformer style games. |
|
|
function Platform::onLevelLoaded(%this, %scenegraph)
{
// Spawn a trigger around the platform.
%trigger = new t2dTrigger() { scenegraph = %scenegraph; class = OneWayTrigger; };
// Disable sending of collisions, so platforms don't collide with the trigger.
%trigger.setCollisionActiveSend(false);
// Set the position and size to match the platform's position and size.
// The trigger is offset below the platform to insure that the trigger is entered.
%trigger.setPositionX(%this.getPositionX());
%trigger.setPositionY(%this.getPositionY() + 1);
%trigger.setWidth(%this.getWidth() + 2);
%trigger.setHeight(%this.getHeight());
// Place in a different graph group than the platforms so player to platform collisions can
// be disabled while leaving player to trigger collisions enabled.
%trigger.setGraphGroup(1);
}
function OneWayTrigger::onEnter(%this, %object)
{
// Set the player to collide with only the trigger's graph group, thus disabling collisions
// with the platforms.
%object.setCollisionGroups(1);
}
function OneWayTrigger::onLeave(%this, %object)
{
// Set the player to collide with the platforms and triggers.
%object.setCollisionGroups(0, 1);
}
function Player::onLevelLoaded(%this, %scenegraph)
{
$player = %this;
// Set up user input. In a real platformer, the input should be much more complex, but this
// will serve the demonstration purposes nicely.
if (isObject(oneWayPlatformMap))
oneWayPlatformMap.delete();
new ActionMap(oneWayPlatformMap);
oneWayPlatformMap.bindcmd(keyboard, left, %this @ ".left = true;", %this @ ".left = false;");
oneWayPlatformMap.bindcmd(keyboard, right, %this @ ".right = true;", %this @ ".right = false;");
oneWayPlatformMap.bindcmd(keyboard, up, %this @ ".jump();", "");
oneWayPlatformMap.push();
// Use two collision iterations so the player moves smoothly along the platforms.
%this.setCollisionMaxIterations(2);
}
function Player::jump(%this)
{
%this.setLinearVelocityY(%this.jumpHeight * -10);
}
function Player::update(%this)
{
%move = %this.right - %this.left;
%this.setLinearVelocityX(%move * %this.moveSpeed);
}
function t2dSceneGraph::onUpdateScene(%this)
{
if (isObject($player) && ($player.getSceneGraph() == %this))
$player.update();
}
And here are the object configurations:
new t2dSceneObjectDatablock(OneWayPlatform)
{
class = "Platform";
CollisionActiveReceive = "1";
Immovable = "1";
};
new t2dSceneObjectDatablock(PlayerConfig)
{
class = "Player";
CollisionActiveSend = "1";
ConstantForce = "0 250";
ConstantForceGravitic = "1";
moveSpeed = "25";
jumpHeight = "15";
};
|



