Javascript P5中光标后面的向量
我已经创建了一个基本的游戏,其中主要对象(矢量播放器)跟随光标,就像在Agar.io中一样。有没有办法将播放器设置为也沿光标方向旋转 我在追求像Stabfish.io一样的旋转效果,即鱼的面始终面向光标Javascript P5中光标后面的向量,javascript,p5.js,Javascript,P5.js,我已经创建了一个基本的游戏,其中主要对象(矢量播放器)跟随光标,就像在Agar.io中一样。有没有办法将播放器设置为也沿光标方向旋转 我在追求像Stabfish.io一样的旋转效果,即鱼的面始终面向光标 function Mover() { this.pos = new p5.Vector(width / 2, height / 2); this.acc = new p5.Vector(0, -10); this.move = () => { //
function Mover() {
this.pos = new p5.Vector(width / 2, height / 2);
this.acc = new p5.Vector(0, -10);
this.move = () => {
// Calculate the acceleration towards the mouse position
this.acc = p5.Vector.sub(new p5.Vector(mouseX, mouseY), this.pos);
this.acc.setMag(10);
// Update the position with the acceleration
this.pos.add(this.acc);
};
this.draw = () => {
push();
// Translate to the object position
translate(this.pos.x, this.pos.y);
// Rotate following the acceleration
rotate(this.acc.heading());
// Draw the object, could be a shape or a sprite or anything
rect(0, 0, 50, 10);
pop();
};
}
let m;
function setup() {
createCanvas(700, 700);
m = new Mover();
}
function draw() {
background(50);
m.move();
m.draw();
}
我已经成功地在地图上对下列光标进行了排序,但我想知道如何解决旋转问题
提前感谢因为您没有提供有关如何编码对象的任何详细信息,所以很难提供与代码匹配的解决方案,但您可能正在寻找提供向量角度的
p5.Vector
类的方法
一种可能的使用方法是这个(您可以测试)。请注意Mover
的draw()
函数如何使用rotate()
和加速度heading()
值来确保对象跟随光标
function Mover() {
this.pos = new p5.Vector(width / 2, height / 2);
this.acc = new p5.Vector(0, -10);
this.move = () => {
// Calculate the acceleration towards the mouse position
this.acc = p5.Vector.sub(new p5.Vector(mouseX, mouseY), this.pos);
this.acc.setMag(10);
// Update the position with the acceleration
this.pos.add(this.acc);
};
this.draw = () => {
push();
// Translate to the object position
translate(this.pos.x, this.pos.y);
// Rotate following the acceleration
rotate(this.acc.heading());
// Draw the object, could be a shape or a sprite or anything
rect(0, 0, 50, 10);
pop();
};
}
let m;
function setup() {
createCanvas(700, 700);
m = new Mover();
}
function draw() {
background(50);
m.move();
m.draw();
}
显然还有更多的代码,但我试图只写与讨论问题相关的内容。谢谢,伙计,这是有意义的,但是我创建的向量略有不同,整个翻译内容有点混淆了我对实际位置的感知-整个画布现在似乎是无限的。如果我和你分享我的源代码,你会乐意提供建议吗?我也可以在我的问题答案中分享代码。我的播放器正在跟踪光标,但我还想显示箭头(例如,在右上角(固定位置).是否有可能创建一个对象,例如,在地图上随机位置收集点,然后每次硬币出现时,箭头指示它在地图上的位置-有点像蛇,你收集点,需要避免即将到来的障碍-问题是实际世界比画布大,所以玩家不知道是什么e硬币出现了。我刚刚开始编码,所以代码可能有点凌乱,下面的代码是根据一些yt教程完成的。它可以工作,但现在的问题是箭头。通常建议编辑您的问题并添加您想要显示的代码,而不是创建答案。现在,无论您如何编写代码,想法仍然是正确的相同:您需要使用
.heading()从当前玩家位置到目标位置的向量
在这个向量上会给你一个介于0和2*PI之间的角度,这是你的玩家需要遵循的方向。现在,无论你想让你的玩家精灵面对这个方向还是另一个精灵,想法都是一样的:你使用平移
移动到你想要绘制精灵的位置……然后使用旋转(角度)
(其中角度
是我前面提到的标题()
),然后可以绘制精灵。您可能希望使用旋转()
和弹出()
环绕和绘图(请参阅)以确保不会弄乱绘图状态,并可以继续在同一参照中绘制下一帧。
translate(width / 2, height / 2);
let newzoom = 30 / player.r;
zoom = lerp(zoom, newzoom, 0.1);
scale(zoom);
translate(-player.pos.x, -player.pos.y);
push();
player.draw();
pop();
player.update();