# Some manual setPosition movement maths help?

Some manual setPosition movement maths help?
0.0 0

#1

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*/

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);

/*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);
}

this.setPosition( moveTo );
}
``````

#2

Here is the code on pasteBucket

http://pastebucket.com/29113

#3

Hi, @Elgan

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

``````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

#4

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 distanceTest = cc.pDistance(this.getPosition(), moveTo); if(distanceTest > distance) { var moveVector = cc.pMult(moveDirection, distance); var moveTo = cc.pAdd(this.getPosition(), moveVector); }`