我开始制作一个Ping Pong游戏的教程,我到达了球应该移动randmoly的部分但是在我的游戏中球只是上升或下降并且摇晃怪异。这是球运动的代码
-(IBAction)StartPoint:(id)sender
{
Y = arc4random() %11;
Y = Y - 5;
X = arc4random() %11;
X = X - 5;
if (Y == 0)
{
Y = 1;
}
if (X == 0)
{
X = 1;
}
timer = [NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(BallMovement)
userInfo:nil
repeats:YES];
}
-(void)BallMovement{
ball.center = CGPointMake(ball.center.x + X, ball.center.y + Y);
if (ball.center.x < 15)
{
X = 0 - X;
}
if (ball.center.x < 305)
{
X = 0 - X;
}
}
答案 0 :(得分:1)
好的,我修复了摇晃的问题,现在球在X中随机移动,但现在我需要让它与边界反弹。
-(IBAction)StartPoint:(id)sender{
Y = arc4random() %11;
Y = Y - 5;
X = arc4random() %9;
X = X - 5;
if (Y == 0) {
Y = 1;
}
if (X == 0) {
X = 1;
}
timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(BallMovement) userInfo:nil repeats:YES]; }
我删除了这部分的代码:
-(void)BallMovement
{
ball.center = CGPointMake(ball.center.x + X, ball.center.y + Y);
//我删除了这部分的条件,球的运动得到了修复。
}
答案 1 :(得分:0)
试一试。这是Bouncing Ball效果它不同的方向电影
-(void)onTimer
{
ball.center = CGPointMake(ball.center.x+pos.x,ball.center.y+pos.y);
if(ball.center.x > 320 || ball.center.x < 0)
pos.x = -pos.x;
if(ball.center.y > 460 || ball.center.y < 0)
pos.y = -pos.y;
}
-(your method)
{
pos = CGPointMake(14.0,7.0);
[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}