Some manual setPosition movement maths help?

Hello,

I am trying to move a sprite using setPosition;

  1. How to i make it framerate indapendant?
  2. How do i make a sprite move at the same speed with different distances?
  3. 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 );
		}

Here is the code on pasteBucket

http://pastebucket.com/29113

Hi, @Elgan

For delta time, you can execute your code in a update call

  1. Add a update function to your node class
update: function(delta) {
     // ...
}
  1. 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.

Huabin

thank you, ill try using that,

collisions should be fine, as i can work out the max distance he can travel, the wall.

I was curious though about the correct way to calculate a distance to move to emulate speed,

edit: with the DeltaTime it seems ok

` speed *= deltaTime;

		var moveVector = cc.pMult(moveDirection, speed);
		var moveTo = cc.pAdd(this.getPosition(), moveVector);

`

then i just check if im moving too far…

var distanceTest = cc.pDistance(this.getPosition(), moveTo); if(distanceTest > distance) { var moveVector = cc.pMult(moveDirection, distance); var moveTo = cc.pAdd(this.getPosition(), moveVector); }

Nice article btw, just overkill for what i need right now, I fear bullet may be also. its only pacman