如何让球从画布的两侧反弹? [英] How do I make a ball bounce off the sides of the canvas?
本文介绍了如何让球从画布的两侧反弹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在画布的所有四面墙周围制作一个球(椭圆形),当发生这种情况时,我还想在每次弹跳后改变球的颜色和速度(当然是随机的)。 P.S我希望球继续在四面墙周围的画布上弹跳。谢谢你的帮助!
我的尝试:
这个是我试过的代码。它从左到右穿过x轴但不会在从右到左的路上停下来。我也不知道如何让它从顶部和底部反弹
I want to make a ball(an ellipse) bounce around all four walls of the canvas and as this happens I would also like to change the colour of the ball and speed after each bounce(randomly of course). P.S I want the ball to continue bouncing around the canvas off all four walls. Thanks for the help!
What I have tried:
This is the code I have tried. It gets the ball across the x-axis from left to right but doesn't stop on the way back from right to left. I also don't know how to get it to bounce off the top and bottom sides
// The position of the ball
var x = 25;
// How far the ball moves every time
var speed = 3;
var draw = function() {
background(47, 222, 126);
fill(48, 46, 48);
ellipse(x, 200, 50, 50);
// Moves the ball
x = x + speed;
if (x > 375) {
speed = -5;
if (x < 214) {
speed = 5;
}
}
};
推荐答案
你的球在x和x都有速度方向。如果没有,它就会来回走动。水平(仅x)或垂直(仅y)。我们假设你有两个。你上面的例子只会改变'x' - 所以你认为y方向会发生什么? ? ?
每当你定义墙的撞击时,你需要考虑物理定律(弹性碰撞:100%动能节能)。
如果垂直墙被击中:
- 水平速度反转100%
- 垂直速度不变
如果击中水平墙:
- 水平速度不变
- 垂直速度反转100%
现在,开始编码。
Your ball has a velocity in both the x and y directions. If it doesn't, it will just go back and forth. Horizontally (x only) or vertically (y only). Let's presume you have both. Your example, above, only changes 'x' - so what do you think will happen in the y direction ? ? ?
Whenever you define an impact with the wall you need to consider the laws of physics (elastic collision: 100% Kinetic Energy conservation).
If the vertical wall is hit:
- the horizontal velocity is reversed 100%
- the vertical velocity is unchanged
If a horizontal wall is hit:
- the horizontal velocity is unchanged
- the vertical velocity is reversed 100%
Now, start coding.
这篇关于如何让球从画布的两侧反弹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文