2011-04-20 21 views
0

當您想在屏幕上的certian位置上實例化對象(例如項目符號)時,代碼是什麼?我自己嘗試過並在互聯網上搜索,但沒有好的例子或基本的Xcode教程來解釋這一點。我不使用Cocos2d。非常感謝幫助:)提前致謝!實例化對象在Xcode中的位置

// 
// 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 

回答

3

如果您正在使用的UIKit:

  1. 創建一個UIImageView含有子彈的UIImage
  2. UIImageView的框設置爲您想要的位置(偏移到中心)和圖像的大小。

簡單的例子:(?)

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

+1:很好解釋.. – Jhaliya 2011-04-20 14:11:18

+0

嘿馬克!很抱歉,遲到的迴應。但我已經嘗試過,但它似乎沒有工作。也許我做錯了什麼?你可以看看我上面包含的腳本,看看有什麼不對嗎? – Amacoder 2011-05-16 10:32:20

+0

我沒有看到你將imageView添加到任何父視圖。 – MarkPowell 2011-05-16 12:44:16

0

也許你已經理解了它,但到了新的UIImageView添加到父視圖,可能是CoreViewController,你必須做一些事情這樣你做了以後有什麼馬克寫道:

[self.view addSubview:imageView]; 

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

在後面的例子中,您決定子視圖的z位置(atIndex),即如果您希望它位於其他子視圖的前面或後面。