在iPhone游戏中控制图像移动

3

我有一段代码,可以在触摸事件中移动UIImage。

代码如下:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[[event allTouches]anyObject];
touchOffset= image.center.x-[touch locationInView:touch.view].x;
}


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch=[[event allTouches]anyObject];
//paddle movemant coordinates
float distanceMoved=([touch locationInView:touch.view].x+touchOffset)- image.center.x;
float newX= image.center.x+distanceMoved;
if(newX>30 &&newX<290)
image.center=CGPointMake(newX, image.center.y);
if(newX>290)
image.center=CGPointMake(290, image.center.y);
if(newX<30)
image.center=CGPointMake(30,  image.center.y);
}

但问题在于,我希望这个操作必须在按钮(左右按钮)动作上执行。每当我按下左侧按钮时,UIImage会稍微向左移动一点。每当我按下右侧按钮时,UIImage会稍微向右移动一点。基本上,我希望通过按钮控制图像只在iPhone或iPad的x轴上移动。感谢您的帮助。

我有点困惑。您有一些检测触摸的UIImages,并将这些图像用作按钮,对吗?为什么不使用UIButtons并将图像嵌入按钮中呢?这样,每当单击按钮时,您都可以拦截执行单击的按钮实例。 - mj_
没听懂你说什么,朋友帮帮我。 - Rocky
2个回答

1
CGRect frame = [image frame];
frame.origin.x += 10.0f;
[image setFrame:frame];

它可以工作,但我想在游戏中使用手柄将对象向左移动和向右移动。 - Rocky

0

CGRect frame = [image frame]; frame.origin.x += 10.0f; [image setFrame:frame]; 使用这个代码并将您的按钮操作与其映射。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接