根据处理速度创建对象的运动.js

Creating an object's movement based on velocity in processing.js

本文关键字:运动 js 创建对象 处理速度      更新时间:2023-09-26

我正在尝试画鸟,它们的翅膀根据它们的速度摆动。简单地说,我的鸟儿飞得越快,它们的翅膀摆动得越快。

的完整代码在下面,它没有做我想要的。我为创建振荡所做的是使flyingFactor根据displayAndMoveWings函数中velocity的大小而变化。然而,当我draw我发现的一切时,因为velocity一直在变化(即由draw函数中的随机acceleration力触发),flyingFactor也是如此,这意味着我的鸟的翅膀根本不会摆动,看起来很麻烦。

有什么方法可以让它工作吗?我希望我的鸟的翅膀看起来像是自然摆动的,只是随着我的鸟加速或减速而更快和更慢。

提前非常感谢!

angleMode = "degrees";
var Bird = function(m,x,y){
    this.mass = m;
    this.position = new PVector(x,y);
    this.velocity = new PVector(0,0);
    this.acceleration = new PVector(0,0);
};
Bird.prototype.applyForce = function(force) {
    var f = PVector.div(force, this.mass);
    this.acceleration.add(f);
};
Bird.prototype.update = function() {
    this.velocity.add(this.acceleration);
    this.position.add(this.velocity);
    this.acceleration.mult(0);
    this.velocity.limit(3);
};
Bird.prototype.displayAndMoveWings = function() {
    this.start=-110;
    this.stop = this.start + 110;
    this.flyingFactor=cos(360+frameCount*this.velocity.mag()*10)*20;
    stroke(0, 0, 0);
    strokeWeight(2);
    noFill();
    arc(this.position.x,this.position.y,this.mass,this.mass,this.start-this.flyingFactor,this.stop-this.flyingFactor);
    arc(this.position.x+this.mass,this.position.y,this.mass,this.mass,this.start+this.flyingFactor-70,this.stop+this.flyingFactor-70);  
};
Bird.prototype.checkEdges = function() {
  if (this.position.x > width) {
    this.position.x = 0;
  } else if (this.position.x < 0) {
    this.position.x = width;
  }
  if (this.position.y > height) {
    this.position.y = 0;
  } else if (this.position.y < 0) {
    this.position.y = height;
  }
};
var bird1 = new Bird(15, width/2, height/2);
var draw = function() {
    background(255, 255, 255);
    bird1.update();
    bird1.displayAndMoveWings();
    var randomAcceleration = new PVector(random(-3,3),random(-3,3));
    bird1.checkEdges();
    bird1.applyForce(randomAcceleration);
};
我想

我可能已经发现了一个黑客...在displayAndMoveWings函数之前,我创建了一个名为 whatIsVelocity 的新全局变量。然后在displayAndMoveWings年我写了以下内容:

if (frameCount % 60 === 0){
    whatIsVelocity = this.velocity.mag();
}
this.flyingFactor=cos(360+frameCount*whatIsVelocity*10)*20;

实际上,这样做是每 60 帧(大约 2 秒)拉动一次速度,并将该速度引入flyingFactor,这意味着它不会像我上面的代码那样每帧都重新计算。不是超级漂亮,但它达到了我的目的。