【问题标题】:How to i direct an object to some other object? Something like a missle?我如何将一个对象指向其他对象?导弹之类的?
【发布时间】:2022-08-18 20:32:56
【问题描述】:
我将如何将对象引导/驱动到光标的位置?
seek 函数应该具有目标的 x 和 y 值,然后将对象引导到这些值
class obj {
constructor(x, y) {
this.x = x
this.y = y
this.ysp = 0
this.xsp = 0
}
draw() {
ctx.fillStyle = \"#fff\"
ctx.beginPath()
ctx.rect(this.x, this.y, 10, 10)
ctx.fill()
}
seek(tx, ty) {
d = distance(this.x, this.y, tx, ty)
}
update() {
this.y += this.ysp
this.x += this.xsp
}
}
标签:
javascript
oop
canvas
【解决方案1】:
为此,您必须使用它们的位置来减少对象和目标之间的距离,如果目标在左侧,则向左移动,如果在右侧则向右移动。上下也一样。
您可能需要多次更新您的位置以以给定的速度移动您的对象,并在每次移动后再次在洞穴上绘制,以便您可以在屏幕上看到移动。
class obj {
constructor(x, y) {
this.x = x
this.y = y
this.ysp = 0
this.xsp = 0
}
draw() {
ctx.fillStyle = "#fff"
ctx.beginPath()
ctx.rect(this.x, this.y, 10, 10)
ctx.fill()
}
seek(tx, ty) {
d = distance(this.x, this.y, tx, ty)
speed = 5 //Note it could be better to use something that adjust itself with the distance depending of the goal
this.x = this.x > tx ? this.x - speed : this.x + speed
this.x = this.y > ty ? this.y - speed : this.y + speed
}
update() {
this.y += this.ysp
this.x += this.xsp
}
}