In our game, we are trying to make a car move straight for 10 seconds after the scene has been launched. However, the car moves tangentially, and eventually falls off the drag strip. Editor - PlayCanvas | HTML5 Game Engine
The code is as follows
var Timer = pc.createScript('timer');
// initialize code called once per entity
Timer.prototype.initialize = function() {
this.timer = 0;
this.entity.rigidbody.angularVelocity = pc.Vec3.ZERO;
this.entity.rigidbody.linearVelocity = pc.Vec3.ZERO;
};
// update code called every frame
Timer.prototype.update = function(dt) {
this.timer += dt;
var fdForce = this.entity.forward.clone();
if (this.timer < 10) {
fdForce.scale(-7);
this.entity.rigidbody.applyForce(fdForce);
}
else {
alert("Race Complete");
}
};
Let’s see, there are several things that aren’t really in place here:
You are creating a force based on the entity forward direction. That is positive X, which isn’t the forward on this case. You need negative Z to have your car move forward based on your map setup.
Then you scale your force by a negative number, that won’t work here.
To move your car that way, constantly by a central force without spinning around its axis you need to zero your angular factor, like this:
You clone and scale a vector per frame in your update method. That allocates so much memory and eventually the garbage collector is going to punish your frame rate. There is no need for that since those values stay constant.
I’ve adapted your script to the following, which seems to work:
var Timer = pc.createScript('timer');
// initialize code called once per entity
Timer.prototype.initialize = function() {
this.timer = 0;
this.entity.rigidbody.angularVelocity = pc.Vec3.ZERO;
this.entity.rigidbody.linearVelocity = pc.Vec3.ZERO;
this.minusZ = new pc.Vec3(0,0,7);
};
// update code called every frame
Timer.prototype.update = function(dt) {
this.timer += dt;
if (this.timer < 10) {
this.entity.rigidbody.applyForce(this.fdForce);
}
else {
alert("Race Complete");
}
};