Jump to content

Stop sprite(velocity.x = 0) after some coordinate


javier_m
 Share

Recommended Posts

Hello,

I have a sprite which has velocity.x=100 moving from {x:0; y: 200}.
I need to set velocity.x=0 (e.g. stop sprite) once sprite reaches the coordinates {x:300; y:200}. How can it be done?

I can't call collide function since there is nothing on that coordinates. I guess I need use the signal? Or any other solution?

Thank you in advance. Any help will be appreciated.

Link to comment
Share on other sites

Hello!

Perhaps you could insert a blank sprite where you want the sprite to stop, and check the collision between only the sprites you want. Then, in the collision callback you set the velocity to 0.

Something like this. Assuming that your sprite is moving horizontally from left to right, and that he must stop regardless of it's Y position:

create : function (){
	//adds sprite at the position needed
	this.checkpoint = this.add.sprite(100, 2);
	//scale the height of the sprite to full height, so the user cannot miss it.
	this.checkpoint.scale.y = this.game.height; 
},
update : function (){
	if (this.checkpoint != null && this.checkOverlap(this.player, this.checkpoint)) 
	{ 
		//perform full stop
		this.player.body.velocity.y = 0;
		this.player.body.velocity.x = 0;

		//set the sprite to null so the collision callback occurs only once. 
		this.checkpoint = null
	}
},
//use a simple function to check the overlap so you won't have to initialize Physics in the collision sprite and save some processing
checkOverlap : function (spriteA, spriteB) {
	var boundsA = spriteA.getBounds();
	var boundsB = spriteB.getBounds();
	
	return Phaser.Rectangle.intersects(boundsA, boundsB);
}

 

I am using a similar logic to trigger various events, I think it should work!

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...