문제

가속도계가있는 바운스 클래스에 서브 클래스 uiview 클래스가 있습니다. 이 바운스 클래스는 이미지를 보여주고 화면에서 움직입니다. iPhone 장치가 이동하면이 이미지가 화면에서 바운스합니다.

여러 인스턴스를 만들 때 마지막 인스턴스 만 작동합니다.

// in the MainViewController.m

Bounce *heart[100];


for(int i = 0; i < 10; i++) {
    rx = (arc4random() % 300) + 10;
    ry = (arc4random() % 300) + 10;
    NSLog(@"random %d %d", rx, ry);
    heart[i] = [[Bounce alloc] initWithPNG:@"Heart.png" 
                       position:CGPointMake(rx, ry) size:CGSizeMake(64, 64)];
    heart[i].velocity = CGPointMake(1.0, 1.0);
    [self.view addSubview: heart[i]];
}

이것은 바운스 클래스입니다.

//
//  Bounce.h
//  iMakeLove
//
//  Created by Giovambattista Fazioli on 06/11/09.
//  Copyright 2009 Saidmade srl. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface Bounce : UIView <UIAccelerometerDelegate> {

    CGPoint     position;
    CGSize      size;
    CGPoint     velocity;
    NSTimer     *objTimer;
    NSString    *pngName;
    CGFloat     bounce;
    CGFloat     gravity;
    CGPoint     acceleratedGravity;
    CGPoint     lastTouch;
    CGPoint     currentTouch;
    BOOL        dragging;

    UIAccelerometer *accelerometer;

}



@property CGPoint position;
@property CGSize size;
@property CGPoint velocity;
@property(nonatomic,retain)NSString *pngName;
@property(nonatomic,retain)NSTimer *objTimer;
@property CGFloat bounce;
@property CGFloat gravity;
@property CGPoint acceleratedGravity;
@property CGPoint lastTouch;
@property CGPoint currentTouch;
@property BOOL dragging;

- (id)initWithPNG:(NSString*)imageName position:(CGPoint)p size:(CGSize)s;

- (void)update;
- (void)onTimer;
- (void)startPrevent;

@end

구현:

//
//  Bounce.m
//  iMakeLove
//
//  Created by Giovambattista Fazioli on 06/11/09.
//  Copyright 2009 Saidmade srl. All rights reserved.
//

#import "Bounce.h"

@implementation Bounce

@synthesize position, size;
@synthesize objTimer;
@synthesize velocity;
@synthesize pngName;
@synthesize bounce;
@synthesize gravity, acceleratedGravity;
@synthesize lastTouch, currentTouch;
@synthesize dragging;



- (id)initWithPNG:(NSString*)imageName position:(CGPoint)p size:(CGSize)s {

    if (self = [super initWithFrame:CGRectMake(p.x, p.y, s.width, s.height)]) {

        [self setPngName:imageName];
        [self setPosition:p];
        [self setSize:s];
        [self setBackgroundColor:[UIColor clearColor]];

        // Set default gravity and bounce

        [self setBounce:-0.9f];
        [self setGravity:0.5f];
        [self setAcceleratedGravity:CGPointMake(0.0, gravity)];
        [self setDragging:NO];

        UIImageView *prezzie = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, s.width, s.height)];

        prezzie.image = [UIImage imageNamed:imageName];

        [self addSubview:prezzie];

        [prezzie release];

        self.accelerometer = [UIAccelerometer sharedAccelerometer];
        self.accelerometer.delegate = self;

    }
    return self;
}

- (void)startPrevent {
    if (objTimer == nil) {
        objTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    }
}


- (void)update {

    [self setNeedsDisplay];

    if(dragging) return;

    velocity.x += acceleratedGravity.x;
    velocity.y += acceleratedGravity.y;
    position.x += velocity.x;
    position.y += velocity.y;

    if(position.x + size.width >= 320.0) {
        position.x = 320.0 - size.width;
        velocity.x *= bounce;
    } else if(position.x <= 0.0) {
        velocity.x *= bounce;
    }

    if(position.y + size.height >= 480.0) {
        position.y = 480.0 - size.height;
        velocity.y *= bounce;
    } else if(position.y <= 0.0) {
        velocity.y *= bounce;
    }
    self.frame = CGRectMake(position.x, position.y, size.width, size.height);
}



- (void)onTimer {
    [self update];
}



- (void)drawRect:(CGRect)rect {

    // Drawing code

}

/* EVENTS */


- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    acceleratedGravity.x = acceleration.x * gravity;
    acceleratedGravity.y = -acceleration.y * gravity;
}



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

    // First, lets check to make sure the timer has been initiated

    if (objTimer == nil) {
        objTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 30.0 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    }

    UITouch *touch = [touches anyObject];

    [self setCurrentTouch:[touch locationInView:self]];
    CGFloat dx = currentTouch.x - position.x;
    CGFloat dy = currentTouch.y - position.y;
    CGFloat dist = sqrt(dx * dx + dy * dy);

    if(dist < size.width) {
        [self setVelocity:CGPointMake(0.0, 0.0)];
        [self setDragging:YES];
    }
    [self setLastTouch:currentTouch];

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    [self setCurrentTouch:[touch locationInView:self]];
    [self setDragging:YES];
    [self setVelocity:CGPointMake(currentTouch.x - lastTouch.x, currentTouch.y - lastTouch.y)];
    [self setLastTouch:currentTouch];

}



- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self setDragging:NO];
}





- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}

- (void)dealloc {
    [super dealloc];
}


@end

도와주세요?

도움이 되었습니까?

해결책

그것은 ~ 때문에 self.accelerometer.delegate = self; 변화하고 있습니다 sharedAccelerometer'대표단과 마지막 과제 만 효과가 있습니다.

다른 팁

나는 가장 앞선 뷰 만 가속기 메시지를 얻을 것이라고 생각합니다. AccelRometer 메시지가 대신 ViewController로 전송되기를 원할 수 있습니다.

내가 여기서 할 수있는 일. (장기적으로 가장 좋은 것은 아니지만 즉각적인 문제를 해결할 것입니다.) 이것은 다음과 같습니다.

나는 가속 중력을 모든 바운스 인스턴스 중에서 공유하는 정적 변수로 만들었습니다. 현실 세계에서 (우리가 시뮬레이션하고있는) 가속 중력은 모든 바운스에 대해 동일하기 때문에 이것은 나에게 텐스트를 만듭니다. (BouncingView와 같은 것으로 바운스 이름을 바꾸 었습니다). 몇 가지 클래스 방법을 통해 해당 변수에 액세스 할 수 있습니다. 또한 가속도계를 공유하고 클래스 방법 인 대표 방법을 가지고 있습니다. 이 물건을 수업에 넣으면 작동해야합니다. (테스트하지만 내 개발 기계는 Apple Store에 고정되어 있습니다.) 또한 게시 한 예제 코드에는 몇 가지 구문 오류가 있습니다.

  static CGCGPoint acceleratedGravity;
  static UIAccelerometer *accelerometer;

    -(void) init {
        /* Everything Else */
        self.accelerometer = [UIAccelerometer sharedAccelerometer];
        self.accelerometer.delegate = self;
        /*Everything Else */
    }

    +(CGPoint) acceleratedGravity {
        return acceleratedGravity;
    }

    +(void) setAcceleratedGravity:(CGPoint) _acceleratedGravity {
        acceleratedGravity = _acceleratedGravity;
    }

+ (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    acceleratedGravity.x = acceleration.x * gravity;
    acceleratedGravity.y = -acceleration.y * gravity;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top