如何使物体的边缘反弹
How to make an object bounce of edge
我正在 JavaScript 中制作一个简单的游戏并使用 Phaser 库。我是新手,所以希望这不是一个愚蠢的问题。
我已经使它们完美运行,但我很想知道如何让岩石弹回墙壁,而不是穿过它们出现在另一边。
跟这个函数有关:
有人告诉我
"If it hits Width: 940 then x = 940 and you start going back 939, i--
, etc. Height will continue as normal. Rather than resetting i.e shot.reset(x, y);
.
If you hit the bottom or top then do the same to height, keeping width the same."
但是,我不确定如何将其实现到代码中。我已经尝试但失败了:)这非常令人沮丧,所以在这件事上的任何帮助都会很棒。
谢谢。
通常,我会创建一个速度矢量,代表我的对象的 "speed"。
在每一帧上,我将该速度矢量添加到位置矢量。当我想让我的物体向相反的方向移动时,我将我的向量乘以 -1。
创建一个这样的矢量,当你的对象碰撞到一条边时,将它乘以 -1。
你可以用这种类型的矢量做很多事情,比如平滑的减速、类空间运动等...
例如:
//on init
var velocity = {x: 10; y: 10};
var pos = {x: 10; y:10};
//on frame update
pos.x += velocity.x;
pos.y += velocity.y
//on edge collision
velocity.x = velocity.x * -1;
velocity.y = velocity.y * -1;
我正在 JavaScript 中制作一个简单的游戏并使用 Phaser 库。我是新手,所以希望这不是一个愚蠢的问题。
我已经使它们完美运行,但我很想知道如何让岩石弹回墙壁,而不是穿过它们出现在另一边。
跟这个函数有关:
有人告诉我
"If it hits Width: 940 then x = 940 and you start going back 939,
i--
, etc. Height will continue as normal. Rather than resetting i.eshot.reset(x, y);
.If you hit the bottom or top then do the same to height, keeping width the same."
但是,我不确定如何将其实现到代码中。我已经尝试但失败了:)这非常令人沮丧,所以在这件事上的任何帮助都会很棒。
谢谢。
通常,我会创建一个速度矢量,代表我的对象的 "speed"。 在每一帧上,我将该速度矢量添加到位置矢量。当我想让我的物体向相反的方向移动时,我将我的向量乘以 -1。
创建一个这样的矢量,当你的对象碰撞到一条边时,将它乘以 -1。
你可以用这种类型的矢量做很多事情,比如平滑的减速、类空间运动等...
例如:
//on init
var velocity = {x: 10; y: 10};
var pos = {x: 10; y:10};
//on frame update
pos.x += velocity.x;
pos.y += velocity.y
//on edge collision
velocity.x = velocity.x * -1;
velocity.y = velocity.y * -1;