I was working on part of a game and was creating gravity with a bouncing ball. I included the project file so you can see what it is doing. It seems to work pretty well except for the hang time before the UIImageView reverses directions and heads back down again. If the UIImageView reaches the top, bottom or a certain speed it reverses direction.
This is just part of me learning new things since I had time this weekend to code again. Is there a better way to calculate gravity in programming?
The reason I am doing this is that I would like to start on a game I played in the early 80's. Some of you might remember the 2 canons with a mountain between them. Every game had a new wind speed and the goal was to destroy your opponents canon by angling the canon and shooting . So I thought this weekend I would play around with creating gravity.
Thanks much for any advise.
This is just part of me learning new things since I had time this weekend to code again. Is there a better way to calculate gravity in programming?
The reason I am doing this is that I would like to start on a game I played in the early 80's. Some of you might remember the 2 canons with a mountain between them. Every game had a new wind speed and the goal was to destroy your opponents canon by angling the canon and shooting . So I thought this weekend I would play around with creating gravity.
Code:
#import "ViewController.h"
float calDistance(float num1, float num2);
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
speed = 1.0;
ballMovment = 0.0;
switchDirection = NO;
downDirection = YES;
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(moveRock)];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)moveRock{
UIImageView *view = (UIImageView*) [self.view viewWithTag:5];
CGRect viewRect = view.frame;
if (downDirection) {
speed *= 1.04;
}
else{
speed *= 0.95; // speed for up direction to slow down
}
// if the speed is below a speed of 0.3 switch directions
float distance = calDistance(ballMovment, speed);
if (distance < 0.3 && !downDirection) {
switchDirection = YES;
}
if (viewRect.origin.y < 0 || viewRect.origin.y > 540 || switchDirection) {
speed = speed * -1; // flip direction
downDirection = (downDirection) ? NO : YES;
switchDirection = NO;
}
// Update the rect
CGRect newRect = CGRectMake(viewRect.origin.x, viewRect.origin.y + speed, viewRect.size.width, viewRect.size.height);
view.frame = newRect;
}
float calDistance(float num1, float num2){
// This calculates the speed of the ball
float number = 0.0;
number = num1 - num2;
if (number < 0) {
number = number * -1;
}
NSLog(@"called %.2f",number);
return number;
}
@end
Thanks much for any advise.