How to add score when ball collide with sprites.
Capital J Productionz

I have viewed a few tutorials but i just can't seem to get my textSprite to update when my ball character collide with any of my object sprites. I have finished the "Breakout game" tutorial series and now trying to add a few other features... So how do i go about doing this?

Here is what i have so far...

// load a scene
wade.clearScene();
wade.loadScene('scene2.wsc', true, function()
{
    // the scene has been loaded, do something here
    
    // Adds score to the second scene when loaded
    var score = 0;
    var scoreText = new TextSprite(score.toString(), '13px Arial' , 'white','left');
    var scoreObject = new SceneObject(scoreText);
    scoreObject.setPosition(-120,-225);
    wade.addSceneObject(scoreObject);

// This is the part where i get stuck cause i am not sure where and what code i am supposed to put to get my score to update when the ball sprite collide with my block sprites (which is junk food in my case.)

//Collision with Junk food and Twizzler Paddle
var rects = this.getOverlappingObjects(true);
for(var i=0; i<rects.length; i++)
{
    if(!rects[i].isPaddle && !rects[i].isBlock)
    {
        continue;
    }
    var vel = this.getVelocity();
    var xAxis = vel.x > 0 ? -1 : 1;
    var yAxis = vel.y > 0 ? -1 : 1;
    var xRad = size.x/2 + rects[i].getSprite().getSize().x/2;
    var yRad = size.y/2 + rects[i].getSprite().getSize().y/2;
    var xOverlap = rects[i].getPosition().x -pos.x;
    var yOverlap = rects[i].getPosition().y -pos.y;
    xOverlap = xOverlap > 0 ? xRad - xOverlap : xRad -xOverlap*-1;
    yOverlap = yOverlap > 0 ? yRad - yOverlap : yRad -yOverlap*-1;
    
    var side = null;
    if(xOverlap < yOverlap)
    {
        this.setVelocity({x:vel.x*-1, y:vel.y});
        this.setPosition(pos.x + xAxis*xOverlap, pos.y);
        side = xAxis > 0 ? 'right' : 'left';
    }
    else
    {
        this.setVelocity({x:vel.x, y:vel.y*-1});
        this.setPosition(pos.x, pos.y + yAxis*yOverlap);
        side = yAxis > 0 ? 'bottom' : 'top';
    }
    if(rects[i].isBlock)
    {
        wade.removeSceneObject(rects[i]);
    }
    break;

 

All 15 Comments
foxcode

Hi Capital, sounds straight forward enough :)

To address the question of where, I would put it near the end of the collision code. So if you want to change the text sprite on collision with a block, I would put it here

if(rects[i].isBlock)
{
    wade.removeSceneObject(rects[i]);
}

This if statement tests that it is indeed a block we have collided with. So in other words when you collide with a block, this code will be executed.

If you want to change a text sprite at this point, you need to do a few things.

  1. Give the scene object that the text sprite belongs to a name. You can then access it using wade.getSceneObject()
  2. Get a reference to the sprite. If the object only has your text sprite you can simply do getSprite(). If this is not the case, I suggest giving your sprite a name, then using getSpriteByName();
  3. Finally, call setText on the textSprite you wish to change.

Your code will look something like this. This is the same block I posted above just with this part added

if(rects[i].isBlock)
{
    var obj  = wade.getSceneObject("nameOfTheObject");
    var text = obj.getSprite(); // or if more than 1 sprite obj.getSpriteByName("textSpriteName");
    text.setText("Whatever text you want to appear"); 
    wade.removeSceneObject(rects[i]);
}

I believe that should work unless I misunderstand what you are after.

Give it a try. If you still have issues please respond to this post, good luck :)
 

Capital J Productionz

Thanks for the help Foxcode, i tried what you suggested but it's not working... I had to put the code under wade.removeSceneObject(rects[i]); cause when i put it above it collisions don't work. Here is my code.

 }
    if(rects[i].isBlock)
    {
        
        wade.removeSceneObject(rects[i]);
        var obj  = wade.getSceneObject("scoreObject");
        var text = obj.getSpriteByName("scoreText"); // or if more than 1 sprite obj.getSpriteByName("textSpriteName");
        text.setText("+=5");

Shri

Capital J,

I'm guessing you are not setting the scene objects name. Add the setName call to your code so it looks like this.

var scoreObject = new SceneObject(scoreText);
scoreObject.setName("scoreObject");
scoreObject.setPosition(-120,-225);

Then change this line

var text = obj.getSpriteByName("scoreText");

To this

var text = obj.getSprite();

And I think it should work

BTW, your set text call will display +=5, if you want to increment the socre by five, then you should have something like this

score += 5;
text.setText(score);

cheers,

Shri

Capital J Productionz

Thanks Shri, i did what you suggested but that's not working either. Heres my code. 

 

// load a scene
wade.clearScene();
wade.loadScene('scene2.wsc', true, function()
{
    // the scene has been loaded, do something here
    
    // Score 
    var score = 0;
    var scoreText = new TextSprite(score.toString(), '13px Arial' , 'white','left');
    var scoreObject = new SceneObject(scoreText);
    scoreObject.setName("scoreObject");
    scoreObject.setPosition(-120,-225);
    wade.addSceneObject(scoreObject);
    

// Score on collisions.

 }
    if(rects[i].isBlock)
    {
        wade.removeSceneObject(rects[i]);
        var obj  = wade.getSceneObject("scoreObject");
        var text = obj.getSprite(); 
        score += 7;
        text.setText(score);

Shri

Capital J,

Did you set the isBlock attribute when you create those scene objects. Something like this ?

// creating my blocks
var obj = new SceneObject(blockSprite);
obj.isBlock = true;

Anyway, rather than wading (no pun intended) throgh your code, I wrote up a little score demo that increments on mouse click.I checked it and I am sure it works. however, it seems we no longer have the abillity upload a zipped file here anymore, so I will put the code here as a snipped.

/****************************************************
//	Ashatej Software
//	July 2016
//	Score Test 
//
*****************************************************/

//----------------------------------------------------------------
//					Wade global functions
//----------------------------------------------------------------

App = function() {
	
	this.GAME_WIDTH = 608;				// the games screen width
	this.GAME_HEIGHT = 920;				// the games screen height
	
	var self = this;
	var score = 0;
	
	//----------------------------------------------------------------
	//					Wade global functions
	//----------------------------------------------------------------
	
	/****************************************************
	// 	Wade global load function
	//	Load scripts, json data files, images and sounds
	*****************************************************/
	this.load = function() {
		console.log('wade global load');
		
	};	// end load

	/****************************************************
	// 	Wade global init function
	//	set the min and max screen sizes based on constants
	//	set the window mode to full
	// 	remove the loading images
	//	start the  demo
	*****************************************************/
	this.init = function() {
		console.log('wade global init');
		wade.setMinScreenSize(self.GAME_WIDTH,self.GAME_HEIGHT);
		wade.setMaxScreenSize(self.GAME_WIDTH,self.GAME_HEIGHT);
		wade.setWindowMode('full');
		wade.setClickTolerance(15);
		 
		self.startDemo();
	};	// end init
	
	
	//----------------------------------------------------------------
	//					Game Management functions
	//----------------------------------------------------------------
	
	this.startDemo = function() {
		console.log('start demo')
		self.createScore();
	};	// end startDemo
	
	//----------------------------------------------------------------
	//					game objects / world creation functions
	//----------------------------------------------------------------
	
	this.createScore = function() {
		var scoreText = new TextSprite(score.toString(), '50px Arial' , 'white','left');
		var scoreObject = new SceneObject(scoreText);
		scoreObject.setName("scoreObject");
		wade.addSceneObject(scoreObject);
	};	// end createScore
	
	
	//----------------------------------------------------------------
	//					Mouse & Input functions
	//----------------------------------------------------------------
	
	this.onClick = function(eventData) { 
		console.log('adding score'); 
		var obj = wade.getSceneObject('scoreObject');
		var text = obj.getSprite();
		score += 100;
		text.setText(score);
	};	// end onClick
	
};	// end App

// For Chrome Debugging
//@ sourceURL=scoreTest.js

So here's what to do

1. copy this code to a file and name it scoreTest.js

2. modify your html file so that it executes the score test script - wade.init('scoreTest.js')

3. if all works ok, then click on the screen and you should see the score incrment by 100's

cheers,

Shri

Capital J Productionz

Thanks for your hard work Shri but for what i am doing i would like if the score would update on a collision with the blocks, (junk food in my case.) I coulkd use this for another project though so thank you for it, i am going to copy it and save it for when i need it. 

echar

Changes in your code:

this.score=0;

var scoreText = new TextSprite(this.score.toString(), '13px Arial' , 'white','left');

 

wade.app.score += 7;

text.setText(wade.app.score);

foxcode

Hi Capital

If you are still stuck, I can take a look if you download your project. Click the download package button, it's right next to save, then select source code, this will download a project zip.

Please email us at clockworkchilli@gmail.com and add your zip as an attachement, I can likely resolve this issue much faster if I can see it for myself, thanks :)

Capital J Productionz

@ Echar made the changes and now the text changes to "NAN" on collide with other sprites and it stays that way on the first collision. Foxcode, i sent the project to you. Thank you guys for all of the much needed help. 

foxcode

Hi Capital

I can't see your message in our gmail "clockworkchilli@gmail.com", looks like it may have fallen down an internet black hole?

 

"NaN" means "Not a number". This can happen when you try to use a none number type as a number, and javascript is unable to convert it for you, for example

Math.floor(5); // This will work, javascript expects a number and is given one
Math.floor("5") // This will usually work. It get's a string but it is smart and converts it to the number 5
Math.floor("hello") // This will produce a NaN error. Javascript is confused, it cannot convert the string "hello" to a number

You're probably not getting this error by calling Math.floor but it is likely to be something similar.

Since email is being weird, I might be able to solve it if you paste 2 bits of code here

The place where you do setText(score) or the equivalent, I need to see what you are passing to the text sprite
 

The place where you declare or set the variable that you put in setText, I need to see what type it is and what transformations it may go through.


We will get there in the end :)



Capital J Productionz

@ Foxcode, I used Math.floor(); as you will see at the end ofd this code, it updates to whatever number i put in but it does not add to the score once it updates. I tried using wade.app.score = Math.floor(+7); as well but it updates the text once and that's it. 

 

// load a scene
wade.clearScene();
wade.loadScene('scene2.wsc', true, function()
{
    // the scene has been loaded, do something here
    
    // Score 
    this.score = 0;
    var scoreText = new TextSprite(this.score.toString(), '13px Arial' ,'white','left');
    var scoreObject = new SceneObject(scoreText);
    scoreObject.setName("scoreObject");
    scoreObject.setPosition(-120,-225);
    wade.addSceneObject(scoreObject);
    

// On collision score code

 }
    if(rects[i].isBlock)
    {
        var obj  = wade.getSceneObject("scoreObject");
        var text = obj.getSprite(); 
        wade.app.score = Math.floor(7);
        text.setText(wade.app.score);
        wade.removeSceneObject(rects[i]);
        
        
        
    
    
    }
    break;
}

 

foxcode

Okay this is an easy problem :)

wade.app.score = Math.floor(7);

All that does is set the score to 7, it will never get larger. You also don't need math floor if you are only ever trying to increment by 7

Simply replace 
wade.app.score = Math.floor(7);

with

wade.app.score += 7;

what this does is take the current score, add 7 to it, and store the result in the score value you created, it is short hand for the following

wade.app.score = wade.app.score + 7;

 

I hope this helps, good luck :)

 


 

Capital J Productionz

@ Foxcode that didn't work either, It produces the same "NaN" error. I even tried this line wade.app.score = wade.app.score + 7; and it still didn't work. I didn't think creating a score on collide would be this difficult but it is (at least for me it is, lol) I don't wanna waste no more time or anybody else time on this so i will just stop here... If i'm having problems just creating a simple score system on collide then i'm never gonna be able to implement some of the more advanced things i had in mind for this game and others. Thanks for all of you guys help, it's greatly appreciated. 

foxcode

Check your private mail Capital J, should be accessible at the top right of the page. Hopefully it works

Capital J Productionz

It works, Thanks once again Foxcode... For those of you who want to know how to create a score off collisions(Adding a score to the breakout tutorial game) check out this out.

Post a reply
Add Attachment
Submit Reply
Login to Reply