太空飞船运动-模拟

Chr*_*ris 6 javascript p5.js

我已经编写了一些代码来模拟具有单个推进器的船舶的无重力运动。在大多数情况下,它可以正常工作,并且船只可以完美地到达目的地,但有时它会无限加速。但我不知道为什么。

seek(target) {
    var desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
    if (desired.mag()>0.1){

        this.orientation = desired;
        if (this.velocity.heading() - desired.heading() > 0.01 && this.velocity.mag() >0.01) {
            this.orientation = this.velocity.copy().mult(-1);
        }

        if ((this.velocity.mag()*this.velocity.mag())/(2*(this.maxForce/this.mass)) > desired.mag()) {
                this.orientation.mult(-1);
        }

        this.applyForce(this.orientation.normalize().mult(this.maxForce/this.mass));
    } else {
        this.velocity = createVector(0,0);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处测试结果:

https://editor.p5js.org/Ahiru/sketches/r1rQ9-T5m

Cha*_*ace 2

船舶物体越过目标的问题是由于星等增量对于船舶移动的增量来说太小而引起的。

为了让飞船对象降落在选定的点上,您需要修改seek方法:

seek(target) {
    var desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
    if (desired.mag()>.01){
Run Code Online (Sandbox Code Playgroud)

物体以增量方式移动,当物体接近目标时,desired.mag 会从大于 0.01 的数值变为当物体经过目标并移开时大于 0.01 的数值。

调整

if (desired.mag() > .01)
Run Code Online (Sandbox Code Playgroud)

if (desired.mag() > 2.0)
Run Code Online (Sandbox Code Playgroud)

例如,船只将被捕获并降落在目标上并停留在那里,直到选择另一个目标。

这是一个工作示例,其中三角洲设置为等于目标的直径,以便船舶看起来降落在目标的表面上。

seek(target) {
    var desired = p5.Vector.sub(target, this.position); // A vector pointing from the location to the target
    if (desired.mag()>.01){
Run Code Online (Sandbox Code Playgroud)
if (desired.mag() > .01)
Run Code Online (Sandbox Code Playgroud)