在Xcode中实现对象的位置

时间:2011-04-20 14:04:27

标签: iphone xcode

当您想要在屏幕上的certian位置实例化对象(例如子弹)时,代码是什么?我自己尝试过,并在互联网上搜索,但没有很好的例子或基本的Xcode教程解释这一点。我不使用Cocos2d。非常感谢帮助:)提前致谢!

//
//  CoreViewController.m
//  Core
//
//  Created by user on 29-04-11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CoreViewController.h"

@implementation CoreViewController

@synthesize ship;
@synthesize bullet;


-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [[event allTouches] anyObject];
    if ([touch view] == ship){

        //ship
        CGPoint location = [touch locationInView:self.view];
        ship.center = location;
    }

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([touch view] == ship){

        //bullet
       // CGPoint blltPos = bullet.center;
        CGPoint shpPos = ship.center;
      //  blltPos.x = blltPos.x += 3;
       // bullet.center = blltPos;

        UIImage *bulletImage = [UIImage imageNamed:@"bullet.png"];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:bulletImage];
        imageView.frame = CGRectMake(shpPos.x, shpPos.y, 60, 60);
    }


}

@end

2 个答案:

答案 0 :(得分:3)

如果您使用的是UIKit:

  1. 创建一个包含UIImageView子弹的UIImage
  2. UIImageView的框架设置为您想要的位置(偏移到中心)和图像的大小。
  3. 快速举例:

    UIImage *bulletImage = [UIImage imageNamed:@"bullet.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:bulletImage];
    imageView.frame = CGRectMake(xLoc, yLoc, bulletImage.size.width, bulletImage.size.height);
    

答案 1 :(得分:0)

也许你已经弄明白了,但是为了将新的UIImageView添加到父视图中,可能(?)CoreViewController,你必须在完成Mark写的之后做这样的事情:

[self.view addSubview:imageView];

[self.view insertSubview:imageView atIndex:0];

在后一个示例中,您决定子视图的z位置(atIndex),即如果您希望它位于其他子视图的前面或后面。