Amacoder
Amacoder

Reputation: 173

Instantiate object on position in Xcode

What is the code when you want to instantiate an object (for example a bullet) on a certian position on screen? I've tried it myself and searched on the internet but there are no good examples or basic Xcode tutorials that explain this. I don't use Cocos2d. Help is much appreciated :) Thanks in advance!

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

Upvotes: 0

Views: 2406

Answers (2)

Emil
Emil

Reputation: 161

Maybe you've already figured it out, but to add the new UIImageView to a parent view, probably(?) the CoreViewController, you'll have to do something like this after you've done what Mark wrote:

[self.view addSubview:imageView];

or

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

In the latter example you decides its z-position (atIndex) of the subviews, i.e if you want it to be in front or behind other subviews.

Upvotes: 0

MarkPowell
MarkPowell

Reputation: 16530

If you are using UIKit:

  1. Create a UIImageView that contains a UIImage of the bullet.
  2. Set the frame of the UIImageView to be the location you want (offset to the center) and the size of the image.

Quick example:

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

Upvotes: 3

Related Questions