【问题标题】:Sprite movement style towards one specific point精灵朝向一个特定点的运动风格
【发布时间】:2014-07-31 10:23:59
【问题描述】:

我的精灵图像将在画布上随机移动。但是在我按下画布后,一个对象会出现,并且精灵图像将以之字形方式向它移动。但我希望精灵直接向对象移动。

我的精灵图像如何移动到我在画布上按下后创建的图像:

Fish.prototype.chaseFood = function(index) {
    if (this.xPos > foodArray[index].x + foodWidth) {
        this.speedX = -1 * Math.abs(this.speedX);
    } else if (this.xPos < foodArray[index].x) {
        this.speedX = Math.abs(this.speedX);
    }
    if (this.yPos > foodArray[index].y + foodHeight) {
        this.speedY = -1 * Math.abs(this.speedY);
    } else if (this.yPos < foodArray[index].y) {
        this.speedY = Math.abs(this.speedY);
    }
};

我知道有一种方法是通过计算精灵点和对象之间的线的斜率来让我的精灵图像移动。但是试了之后还是拿不到。有人知道如何实现吗?

【问题讨论】:

    标签: javascript html canvas sprite


    【解决方案1】:

    你可以将你的代码更改为以下的chaseFood

    Fish.prototype.chaseFood = function (index) {    
        var tx = foodArray[index].x + foodWidth - this.xPos,
            ty = foodArray[index].y + foodHeight - this.yPos,
            dist = Math.sqrt(tx*tx+ty*ty); // better ways to do the distance.
    
            // 1 can be any speed value to make it go faster or slower
            this.speedX = (tx/dist)*1;
            this.speedY = (ty/dist)*1;
    };
    

    它的作用是获取鱼和食物之间的距离,并将当前的 x 和 y 分量除以使其以恒定速度向食物移动的距离。你的总是 1 或 -1,所以它会来回反弹,这种方法允许它是一个浮动,所以它可以准确地向食物移动。

    我修改了代码from an article on my blog,它还有其他有用的方法来解决这类问题。

    Live Demo

    【讨论】:

    • 嗨,是否可以让精灵图像游向它?取而代之的是诡异的移动方式。意思是鱼的嘴会朝向食物,身体在后面。
    • @Bernard 是的,它涉及更多数学。但是,您的问题和代码并没有真正表明:P 如果您想了解有关如何操作的更多信息,请查看答案中的链接而不是我给您代码!
    猜你喜欢
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多