//
// AppDelegate.m
// Demo-UI2-2
//
// Created by dllo on 15/3/5.
// Copyright (c) 2015年 luojin. All rights reserved.
//
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (void)dealloc
{
[_block release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
_yVelocity = 1.0;
_xVelocity = 1.0;
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window makeKeyAndVisible];
/*
CGRect rect2 = CGRectMake(200, 80, 50, 50);
UIView *bView = [[[UIView alloc] initWithFrame:rect2] autorelease];
[bView setBackgroundColor:[UIColor greenColor]];
[self.window addSubview:bView];
[bView setTag:200];
*/
CGRect rect = CGRectMake(40, 40, 50, 50);
UIView *aView = [[[UIView alloc] initWithFrame:rect] autorelease];
[self.window addSubview:aView];
[aView setBackgroundColor:[UIColor redColor]];
[aView setTag:100];
//成圆
[aView.layer setCornerRadius:25];
//用定时器定时调用改变AView位置的方法
[NSTimer scheduledTimerWithTimeInterval:0.003 target:self selector:@selector(changePosition) userInfo:nil repeats:YES];
//设置一个固定不动的视图, 作为障碍物,若碰撞则aView停止运动
//创建block
_block = [[UIView alloc] initWithFrame:CGRectMake(160, 250, 50, 50)];
[_block setBackgroundColor:[UIColor cyanColor]];
[self.window addSubview:_block];
return YES;
}
//改变AView位置的方法
- (void)changePosition
{
UIView *aView = [self.window viewWithTag:100];
//视图向下移动一个像素
CGRect rect = [aView frame];
rect.origin.y += _yVelocity;
rect.origin.x += _xVelocity;
[aView setFrame:rect];
//碰撞上边界
if (rect.origin.y + rect.size.height == self.window.bounds.size.height) {
_yVelocity = -1.0;
}
//碰撞下边界
if (rect.origin.y == 0) {
_yVelocity = 1.0;
}
//碰撞左边界
if (rect.origin.x + rect.size.width == self.window.bounds.size.width) {
_xVelocity = -1.0;
}
//碰撞右边界
if (rect.origin.x == 0) {
_xVelocity = 1.0;
}
//检测是否碰撞
if (CGRectIntersectsRect(aView.frame, _block.frame)) {
//停止运动
// _xVelocity = 0.0;
_yVelocity = 0.0;
//将障碍物打没
// [_block setHidden:YES];
//碰撞之后反弹
//判断碰撞的是哪个边界 (碰撞产生的矩形)
}
/*
UIView *bView = [self.window viewWithTag:200];
CGRect rect2 = [bView frame];
rect2.origin.y += _yVelocity;
rect2.origin.x += _xVelocity;
[bView setFrame:rect2];
//碰撞下边界
if (rect2.origin.y + rect.size.height == self.window.bounds.size.height) {
_yVelocity = -1.0;
}
//碰撞下边界
if (rect2.origin.y == 0) {
_yVelocity = 1.0;
}
//碰撞左边界
if (rect2.origin.x + rect.size.width == self.window.bounds.size.width) {
_xVelocity = -1.0;
}
//碰撞右边界
if (rect2.origin.x == 0) {
_xVelocity = 1.0;
}
*/
}