【问题标题】:Stop Movement on Collision碰撞时停止运动
【发布时间】:2014-11-19 11:05:18
【问题描述】:

我正在用 Javascript 创建一个小游戏,并创建了一个碰撞检测功能,可以检测我的 2 张图像何时发生碰撞。我有一个玩家图像和敌人图像,我用箭头键移动玩家。当我与敌人的图像发生碰撞时,我希望玩家不能越过图像但仍然能够移动,例如与墙壁或其他东西碰撞。我真的不知道该怎么做,所以我不能提供示例代码,但我可以给你我的碰撞函数和播放器对象;

//播放器对象

var playerImg = new Image();
playerImg.src = "../Images/player.png";
var playerReady = false;
playerImg.onload = function(){
        playerReady = true;
};
var player = {
        x: 300,
        y: 150,
        speed: 200
};

//碰撞功能

function CollisionCheck(Img1, Img2, Obj1, Obj2, width){
    var colliding = false;

    if(Obj1.x < Obj2.x + width && Obj1.x + width > Obj2.x && Obj1.y < Obj2.y + width && Obj1.y + width > Obj2.y){
        colliding = true;
    }else{
        colliding = false;
    }

    return colliding;
}

也许我可以检测到碰撞发生在哪一侧并阻止玩家在碰撞时向图像移动?

我调用函数:

if(CollisionCheck(player, enemy, 32)){

}

【问题讨论】:

  • 您可以在移动对象之前针对预期位置进行碰撞检查,并且只有在该点没有碰撞时才移动。

标签: javascript html5-canvas 2d


【解决方案1】:
function checkTouching(img1, img2)
{
    // checks if the two images are touching at any coordinate
    // given two objects with x, y, width, and height
    var touching =
        img1.x + img1.width >= img2.x
        && img1.x <= img1.x + img1.width
        && img1.height + img1.y >= img2.y
        && img2.y <= img2.y + img2.y;

    if (touching)
    {
        // images are touching
    }
    else
    {
        // images aren't touching
    }
}

【讨论】:

  • 有点晚了,希望你还需要。
猜你喜欢
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多