How do i make a sprite move at the same speed with different distances?
How can i improve the code for max distances?
//newSpritePosition = worked out max point before hitting a wall
var distance = cc.pDistance(this.getPosition(), newSpritePosition);
/*if we are away from the wall*/
console.log("distance " + distance);
if(distance > 0)
{
var speed = this._speed;
/*HOW TO MAKE IT SMOOTH*/
/*attempt to think about framerates*/
var deltaTime = 0;
/*HOW DO I GET DELTA TIME?*/
speed *= deltaTime;
/*set how fast to move over this distance*/
/*HOW DO I SET A "SAME SPEED" FOR ANY VARIABLE DISTANCEW*/
var moveSpd = 10;
/* moveDirection = point cc.p(0,1) etc */
var moveVector = cc.pMult(moveDirection, moveSpd);
var moveTo = cc.pAdd(this.getPosition(), moveVector);
/*COLLISION, */
/*HJOW CAN I MAKE THIS MORE EFFICIENT FOR MAX DISTANCE*/
var distanceTest = cc.pDistance(this.getPosition(), moveTo);
if(distanceTest > distance)
{
/*rebuild our new position at max distance*/
var moveVector = cc.pMult(moveDirection, distance);
var moveTo = cc.pAdd(this.getPosition(), moveVector);
}
this.setPosition( moveTo );
}
For delta time, you can execute your code in a update call
Add a update function to your node class
update: function(delta) {
// ...
}
Start the schedule update with this line
this.scheduleUpdate();
For the stable speed, as soon as the framerate is stable, the speed stay constant, then there won’t be any problem.
But the collision is a topic far more complicated, I suggest you can study some classic collision detection algorithm, like Separate Axis Theorem.
Otherwise, you can also use Chipmunk which can be found in our engine’s external folder. It’s really a great physic engine.