「这是我参与11月更文挑战的第15天,活动详情查看:2021最后一次更文挑战」
创建弹出小鸟的弹弓
在 js 文件夹下创建一个 slingshot.js,然后添加到 inidex.html
文件中。
class SlingShot{
constructor(x, y, body){
const options = {
pointA:{
x:x,
y:y
},
bodyB:body,
stiffness:0.5,
length:20
}
this.sling = Constraint.create(options);
Composite.add(world,this.sling);
}
}
定义一个 SlingShot 类,构造函数接受 x,y 以及 body 函数,其中定义了橡皮筋的物理参数如下
- stifness
刚度是材料力学中的名词,定义为施力与所产生变形量的比值,表示材料或结构抵抗变形的能力。公式记为 其中k 表示刚度,P 表示施力, 表示变形量。在国际单位制中,刚度的单位为牛顿/米。一般应用于虎克定律作系统的振动分析。
- stiffness 接收一个数字,用于指定约束的刚度,返回到静止状态的约束长度的速度。值为1意味着约束应该是非常硬的。值为 0.2 意味着约束的行为像弹簧。
class SlingShot{
constructor(x, y, body){
...
}
show(){
stroke(255);
const posA = this.sling.pointA;
const posB = this.sling.bodyB.position;
line(posA.x,posA.y,posB.x,posB.y)
}
}
然后我们绘制一条线用于将弹弓表示出来。
function setup() {
...
bird = new Bird(50,300,25);
slingShot = new SlingShot(50,300,bird.body)
...
}
释放弹出小鸟
监听按下空格键,然后释放小鸟
function keyPressed(){
if(key === ' '){
console.log('spacebar')
}
}
在 SlingShot 添加 fly 方法,其中将 this.sling.bodyB
设置为 null
。
fly() {
this.sling.bodyB = null;
}
还需要在弹出小鸟时,关闭绘制线,否则就会 this.sling.bodyB
为 null
的错误。
show(){
if(this.sling.bodyB){
stroke(255);
const posA = this.sling.pointA;
const posB = this.sling.bodyB.position;
line(posA.x,posA.y,posB.x,posB.y)
}
}
然后我们将弹出小鸟工作交个释放鼠标的事件。
function mouseReleased() {
setTimeout(() => {
slingShot.fly();
}, 100);
}
到现在为止我们已经大体搭建好动力系统,接下里就是一些细化丰满的工作了。