以你的例子,我假设你并不打算让怪物和人类对彼此做出反应。
无论哪种方式,向世界添加自定义接触侦听器,并在接触侦听器中检查玩家和敌人形状是否创建了接触点。如果是这样,对 playerbody 应用linearimpulse() 以达到您想要的效果并禁用用户的所有键输入以防止运动发生任何变化。然后在 player 上设置一个属性,防止它在被怪物击中时应用冲动。
此外,当您创建身体时,您需要将玩家和敌人实例设置为 body.UserData()
public class Player extends MovieClip
{
public const MAX_EFFECT_TIME = 1.5 * framerate;
public var effectTime:int = 0;
public var body:b2Body;
public function step():void
{
if (effectTime > 0)
{
effectTime--;
//do awesome animation
}
else
{
//move normally
}
}
public function Hit(enemy:Enemy)
{
if (effectTime == 0)
{
//apply linear impulse to object
if (enemy.body.GetPosition().x < this.body.GetPosition().x)
{
//apply impulse left in left direction
b2Vec2 force = b2Vec2(-8, 10);
body.ApplyLinearImpulse(force, body.GetWorldCenter());
}
else
{
//apply impulse in right direction
b2Vec2 force = b2Vec2(8, 10);
body.ApplyLinearImpulse(force, body.GetWorldCenter());
}
//reset effect time
effectTime = MAX_EFFECT_TIME;
}
}
}
public class Game extends MovieClip
{
public var world:b2World;
public var player:Player;
public Game()
{
world = initWorld();
player = initPlayer();
var cl = new CustomContactListener();
world.SetContactListener(cl);
this.addEventListener(Event.ENTER_FRAME, step);
}
private void step(e:Event)
{
world.step();
player.step();
}
}
public class CustomContactListener extends b2ContactListener
{
//Called when a contact point is added.
public override function Add(point:b2ContactPoint):void
{
//checks if the first shape is a player and second is an enemy if true call Hit
if (point.shape1.GetBody().GetUserData().isPlayer && point.shape2.GetBody().GetUserData().isEnemy)
{
point.shape1.GetBody().GetUserData().Hit(point.shape2.GetBody().GetUserData());
}
else if (point.shape2.GetBody().GetUserData().isPlayer && point.shape1.GetBody().GetUserData().isEnemy)
{
point.shape2.GetBody().GetUserData().Hit(point.shape1.GetBody().GetUserData());
}
}
}
然后您可以根据需要编辑值。希望这会有所帮助,祝你好运!