How to add 1 to the score each time an object's y coordinate is equal to another object's y coordinate - ios

i have a game where the user must move the ball in a vertical way between 2 objects , i want to have a scoring system that allows me to add 1 to the score each time the ball is equal to the 2 objects so i tried the code below but it is not working probably,it is not adding one each time the ball's y coordinates are equal to the object's y cooridnates.
if(imageview.center.y == imageview1.center.y){
int score = score + 1;
scorelabel.text = [NSString stringWithFormat:#"%i",score];
}

As I assume your imageview.centre.y will be different then imageView1.centre.y .Also you could use this method CGRectIntersection(<#CGRect r1#>, <#CGRect r2#>) and place your both frame in provided fields. So it will notify whenever there is an intersection of two frames. Code will be like -
if (CGRectIntersectsRect(self.pacman.frame, self.exit.frame))
{
//Wirte your score handling code here...
}
else
{
//Skip or do what you want...
}
Hope this might help you.

Your variable is recreated every time your if is performing.
Define it somewhere before #implementation
int score = 0;
And replace int score = score + 1; with score++

As comment you should be aware of comparison of double. See This Question for details

Related

How do I detect if a number is a decreasing or increasing number? iOS

I'm using a SpriteKit game engine within XCode while developing a game that bounces a ball and platforms come from the sky and the objective is to bounce on the platforms to get higher. I need to add a velocity to the ball when it falls down + comes in contact with a platform. I'm having trouble trying to detect the balls Y position. I had something like this in the update method but nothing happens... I'm open to suggestions.
//The value of the _number instance variable is the Y position of the ball.
if (_number++) {
NSLog(#"UP");
}
if (_number--) {
NSLog(#"DOWN");
}
You can see a node's position by using code like this:
if(myNode.position.y > 0)
NSLog(#"y is greater than 0");
If you want to check a node's current speed (vector) you can do it like this:
if(myNode.physicsBody.velocity.dy > 0)
NSLog(#"Moving up");
if(myNode.physicsBody.velocity.dy < 0)
NSLog(#"Moving down");
Remember that position and speed (vector) are not the same thing.
You need to read the SKPhysicsBody docs to understand about CGVector and other important issues.
Alright, this:
if (_number++) {
NSLog(#"UP");
}
if (_number--) {
NSLog(#"DOWN");
}
doesn't work to do anything. It shouldn't even run. I don't why it doesn't give an error.
number++; is a simplified form of
number = number + 1;
You can't place it in an if statement.
First make the variable #property int ypos in your header.
Then every update compare the current y to the ypos.
After comparing, save the current y to ypos.
Place this in your Update method.
if (ball.position.y > _ypos)
{
//going up
}
else if (ball.position.y < _ypos)
{
//going down
}
_ypos = ball.position.y;
P.S. I haven't had access to a computer so the formatting might suck from my phone

Speed up/Slow down an object once it collides with an object

I'm currently working on a 2D platformer and I'm wondering if I can get any tips on how to increase the speed that an object moves at for a few seconds after it collides with another object.
First you need a variable called velocity
Vector2 velocity = new Vector2(0.0f, 0.0f);
Every update, you change the Rectangle of the sprite by the velocity.
rectangle.X += (int)velocity.X;
rectangle.Y += (int)velocity.Y;
Then, you can change the velocity however you like and it will change the speed.
//slow down
velocity.X -= 10;
velocity.Y -= 10;
//speed up
velocity.X += 10;
velocity.Y += 10;
You can also change the X and Y values for velocity individually, like this:
velocity.Y += 10;
That will make the sprite move down when typed in.
Hope this helped! Tell me if you need any clarification!
First you want to have it react to the collision, so in the method you're using to detect the collision, add a call to a new method in your object. Let's call it SpeedUp(). It should look something like this:
public void SpeedUp()
{
_speedUpTimer = 0;
IsSpedUp = true;
_maxVelocity.X = SpedUpVelocity.X;
}
where _speedUpTimer is a variable in your object's class (or whatever component handles movement), _maxVelocity is whatever variable maintains your object's top speed, and SpedUpVelocity is the constant or variable holding the faster velocity. IsSpedUp should be initialized as false. You're also going to want a constant or variable to hold the amount of time you want the object to be faster, such as SpeedUpTime.
Then, in your object's Update(), add the lines
_speedUpTimer += gameTime.ElapsedGameTime.Milliseconds;
if (IsSpedUp && _speedUpTimer > SpeedUpTime)
{
_maxVelocity.X = UsualMaxVelocity.X;
IsSpedUp = false;
}
UsualMaxVelocity will hold your object's previous, non-sped-up maximum velocity, which your object will return to using after the timer is up.
Of course, you can always make your Y velocity increase, but I assumed you just wanted horizontal speed.

Score system not working Obj-C

So i am developing a game and have coded the score system. I want it to be so that when my object that is scrolling down is equal to the same y.co-ordinate as the "Box" object, the score system adds one to the score.
However, upon trying this the socre does not update and stays at 0. Im not quite sure why, could you please tell me where I may be going wrong and how i could fix it.
This is the code I am using to code the score system. Any help would be appreciated, thanks.
-(void)Score{
ScoreNumber = ScoreNumber + 1;
ScoreDisplay.text = [NSString stringWithFormat:#"%i", ScoreNumber];
}
[There is also some code in the view did all. but the problem is not with this part of the code as i have used it before and it works fine.]
This is where it is meant to be implemented but is not working...
if (ROne.center.y == IView.center.y) {
[self Score];
}
if (RTwo.center.y == IView.center.y) {
[self Score];
}
if (RThree.center.y == IView.center.y) {
[self Score];
}
if (RFour.center.y == IView.center.y) {
[self Score];
}
if (RFive.center.y == IView.center.y) {
[self Score];
}
if (RSix.center.y == IView.center.y) {
[self Score];
}
Your problem is likely that is the y-increment doesn't add up to the y-coordinate of the target object, then it won't be strictly equal. You'll just sort of pass by it. This is why >= worked, except once you passed it, it will keep adding to the score.
So, what you need to test for is "passing by". That is to say that prior to moving, ROne.center.y < IView.center.y and after moving ROne.center.y >= IView.center.y. That is the only condition that effectively check for "ROne just arrived at the desired height".
Alternatively, you can use >= and use a flag arrived on ROne to tell it to quit counting the score. Set the arrived flag to false when (ROne.center.y >= IView.center.y && ROne.arrived) is true. Then reset the arrived flag to true when you decide to reset the object to the top of the screen.
You need to think through the logic of your game code:
Some object is moving along the Y-axis each frame and that movement is likely to be more than 1 pixel (or point) per frame.
Your tick method is being called each frame (or some other set interval) and it's coded to only work when the Y-coordinate exactly matches the boundary you have set.
What's happening is the object is moving past the boundary between ticks and the method is therefore unable to detect it (i.e. think about a boundary where y == 3 and the object goes from y == 1 to y == 5 in a single tick).
What you need to do is hold a flag showing if the object has gone past the boundary and only check if the boundary condition if this flag is false. The best place to put this flag is in the object itself.
Something like:
if (!ROne.hasScored && ROne.center.y => IView.center.y) {
[self Score];
ROne.scored = YES;
}
You also need to consider using an array of the six objects, rather than 6 individual variables.

using CGRectIntersectsRect for updating score of my game

I am trying to update my score using CGRectIntersectsRect and I want to increment in my score every time two images collide with each other. But, my score does not show periodicity some times it increases by one unit but it increases randomly when two UIimages collide with higher speed. Here is my code:
-(void)Collision{
if (CGRectIntersectsRect(Ball.frame, Player.frame)) {
PlayerScoreNumber = PlayerScoreNumber + 1;
PlayerScore.text = [NSString stringWithFormat:#"%i", PlayerScoreNumber];
Y = arc4random() %5;
Y = 0-Y;
}
The two UIImages are 'ball' and 'racket' , I want to increment in my score every time the ball strikes the racket. Please help...
I suspect you are counting the same collision twice (or more) and so you are going to have to keep state about the collision and remember when you've already seen the current collision:
Create a new instance variable in your implementation file, something like:
#interface MyClass ()
{
BOOL _ballCollidedWithPlayer;
}
and manage the state like this:
-(void)Collision{
BOOL collided = CGRectIntersectsRect(Ball.frame, Player.frame);
if (collided) {
if (_ballCollidedWithPlayer)
return; // Nothing to do; we already know about this collision
PlayerScoreNumber = PlayerScoreNumber + 1;
PlayerScore.text = [NSString stringWithFormat:#"%i", PlayerScoreNumber];
Y = arc4random() %5;
Y = 0-Y;
}
_ballCollidedWithPlayer = collided;
}

multi image collision detection

heres the problem
i have 5 balls floating around the screen that bounce of the sides, top and bottom. thats working great.
what i want to do now is work out if any of them collide with each other.
i know about
if (CGRectIntersectsRect(image1.frame, image2.frame))
{
}
but that only checks two images, i need to check all and each of them..
ive checked everywhere but cant find the answer, only others searching the same thing, any ideas?
thanks in advance
Spriggsy
edit:
im using this to find the CGRect and store it in an array
ball1 = NSStringFromCGRect(image1.frame);
ball2 = NSStringFromCGRect(image2.frame);
ball3 = NSStringFromCGRect(image3.frame);
ball4 = NSStringFromCGRect(image4.frame);
ball5 = NSStringFromCGRect(image5.frame);
bingoarray = [NSMutableArray arrayWithObjects:ball1,ball2,ball3,ball4,ball5,nil];
this then gets passed to a collision detection method
-(void)collision {
for (int i = 0; i<[bingoarray count]-1 ; i++) {
CGRect ballA = CGRectFromString([bingoarray objectAtIndex:i]);
if (CGRectIntersectsRect(ballA, image1.frame)) {
NSLog(#"test");
}
}
this i guess should check one ball against all the others.
so ball 1 gets checked against the others but doesnt check ball 2 against them. is this nearly there?
}
The ideal solution is to store all the rectangles into a interval tree or a segment tree in order to efficiently compute any overlapping areas. Note that you will have to generalize to 2 dimensions for your use case.
Another efficient approach would be to use a K-d tree to find the nearest other balls and compare against the nearest neighbor until there isn't a collision.
The simple approach is to simply iterate over all the balls and compare them to all other balls with a higher ID (to avoid double checking ball1 -> ball2 and ball2 -> ball1).
Since you only have 5 at once, the iterative approach is likely fast enough to not be dropping frames in the animation, but you should consider a more scalable solution if you plan to support more balls since the simple appreach run in quadratic time.
That is a fun little math problem to avoid being redundant.
You can create an array of the images. And loop through it, checking if each member collides with any successive members.
I can spell it out more with code if need be.
EDIT I couldn't resist
// the images are in imagesArray
//where you want to check for a collision
int ballCount = [imagesArray count];
int v1Index;
int v2Index;
UIImageView * v1;
UIImageView * v2;
for (v1Index = 0; v1Index < ballCount; v1Index++) {
v1 = [imagesArray objectAtIndex:v1Index];
for (v2Index = v1Index+1; v2Index < ballCount; v2Index++) {
v2 = [imagesArray objectAtIndex:v2Index];
if (CGRectIntersectsRect(v1.frame, v2.frame)) {
// objects collided
// react to collision here
}
}
}

Resources