-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBall.m
More file actions
74 lines (57 loc) · 1.82 KB
/
Ball.m
File metadata and controls
74 lines (57 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* TouchesTest (c) Valentin Milea 2009
*/
#import "Ball.h"
#import "Paddle.h"
@implementation Ball
@synthesize velocity;
- (float)radius
{
return self.texture.contentSize.width / 2;
}
+ (id)ballWithTexture:(CCTexture2D *)aTexture
{
return [[[self alloc] initWithTexture:aTexture] autorelease];
}
- (void)move:(ccTime)delta
{
self.position = ccpAdd(self.position, ccpMult(velocity, delta));
if (self.position.x > 320 - self.radius) {
[self setPosition: ccp( 320 - self.radius, self.position.y)];
velocity.x *= -1;
} else if (self.position.x < self.radius) {
[self setPosition: ccp(self.radius, self.position.y)];
velocity.x *= -1;
}
}
- (void)collideWithPaddle:(Paddle *)paddle
{
CGRect paddleRect = paddle.rect;
paddleRect.origin.x += paddle.position.x;
paddleRect.origin.y += paddle.position.y;
float lowY = CGRectGetMinY(paddleRect);
float midY = CGRectGetMidY(paddleRect);
float highY = CGRectGetMaxY(paddleRect);
float leftX = CGRectGetMinX(paddleRect);
float rightX = CGRectGetMaxX(paddleRect);
if (self.position.x > leftX && self.position.x < rightX) {
BOOL hit = NO;
float angleOffset = 0.0f;
if (self.position.y > midY && self.position.y <= highY + self.radius) {
self.position = CGPointMake(self.position.x, highY + self.radius);
hit = YES;
angleOffset = (float)M_PI / 2;
}
else if (self.position.y < midY && self.position.y >= lowY - self.radius) {
self.position = CGPointMake(self.position.x, lowY - self.radius);
hit = YES;
angleOffset = -(float)M_PI / 2;
}
if (hit) {
float hitAngle = ccpToAngle(ccpSub(paddle.position, self.position)) + angleOffset;
float scalarVelocity = ccpLength(velocity) * 1.05f;
float velocityAngle = -ccpToAngle(velocity) + 0.5f * hitAngle;
velocity = ccpMult(ccpForAngle(velocityAngle), scalarVelocity);
}
}
}
@end