繁体   English   中英

JavaScript canvas使对象朝对象射击

[英]JavaScript canvas make object shoot toward object

我是JavaScript新手,正在创建一种射击游戏。 我要使一个对象移向另一个对象。 因此,“子弹”获得了“猎物”的位置,它将朝着它移动。 我不知道如何实现,我在互联网上找不到任何类似的东西。 因此,我首先尝试了一些简单的方法:

在以下代码中,“项目符号”移到左侧。 如何指定将其移向对象? 我有2个对象。 应该是敌人子弹对象(不是子弹对象),它应该朝向另一个对象。 PS:英语不是我的母语。 抱歉,造成任何混乱。

     this.draw = function () {
            this.context.clearRect(this.x + 2, this.y + 1.5, this.width - 4.5, this.height);
//x+ the speed make it go to the left
            this.x += this.speed;
            if (self === "bullet" && this.x >= this.canvasWidth) {
                return true;
            }
            else if (self === "enemyBullet" && this.x >= 1000) {
                console.log(this.x);
                return true;
            }
            else {
                if (self === "bullet") {
                    this.context.drawImage(imageRepository.bullet, this.x, this.y);
                }
                else if (self === "enemyBullet") {
                    this.context.drawImage(imageRepository.enemyBullet, this.x, this.y);
                }
                return false;
            }
        };

归一化向量

您需要找到从一个对象到下一个对象的归一化向量。 向量只是具有方向和长度的箭头。 在这种情况下,我们将长度标准化,即使其等于1个单位长。 我们这样做是为了在使用矢量时可以轻松设置速度。

将向量从一个点返回到下一个的函数

// Code is in ES6
// fx, fy is from coordinate
// tx, ty is to coordinate
function getNormVec(fx, fy, tx, ty){
    var x = tx - fx;  // get differance
    var y = ty - fy;
    var dist = Math.sqrt(x * x + y * y); // get the distance.
    x /= dist;  // normalised difference
    y /= dist;
    return {x,y};
} 

一旦有了向量,就可以通过将向量乘以速度来移动对象。 创建子弹并将其从myObj移至myTarget

var myObj = {}
var myTarget = {};
var myBullet = {}
myObj.x = 100;
myObj.y = 100;
myTarget.x = 1000
myTarget.y = 1000

var vecToTag = getNormVect(myObj.x, myObj.y, myTarget.x, myTarget.y);
myBullet.nx = vecToTag.x; // set bullets direction vector
myBullet.ny = vecToTag.y;
myBullet.x = myObj.x; // set the bullet start position.
myBullet.y = myObj.y;
myBullet.speed = 5; // set speed 5 pixels per frame

移动子弹

myBullet.x += myBullet.nx * myBullet.speed;
myBullet.y += myBullet.ny * myBullet.speed;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM