首页 文章 精选 留言 我的

精选列表

搜索[ios],共10000篇文章
优秀的个人博客,低调大师

[IOS]陀螺仪和加速仪编程

如何实现iPhone的重力感应还有旋转感应,也就是术语上的陀螺仪和加速器?下面我们来用一个简单的Demo入门一下吧! 由于模拟器上不能运行这个,所以只能贴出代码,没有截图。 ViewController.h: #import <UIKit/UIKit.h> @interface BIDViewController : UIViewController<UIAccelerometerDelegate> @property (weak, nonatomic) IBOutlet UILabel *accelerometerLabel; @property (weak, nonatomic) IBOutlet UILabel *gyroscopeLabel; @end ViewController.m: #import "BIDViewController.h" #import <CoreMotion/CoreMotion.h> @interface BIDViewController () @property (strong, nonatomic) CMMotionManager *motionManager; @property (strong, nonatomic) NSOperationQueue *queue; @end @implementation BIDViewController - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.motionManager = [[CMMotionManager alloc] init]; self.queue = [[NSOperationQueue alloc] init]; if (self.motionManager.accelerometerAvailable) { self.motionManager.accelerometerUpdateInterval = 1.0 / 10.0; [self.motionManager startAccelerometerUpdatesToQueue:self.queue withHandler: ^(CMAccelerometerData *accelerometerData, NSError *error) { NSString *labelText; labelText = [NSString stringWithFormat: @"Accelerometer\n-----------\nx: %+.2f\ny: %+.2f\nz: %+.2f", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z]; NSLog(@"%@",labelText); }]; } else { self.accelerometerLabel.text = @"This device has no accelerometer."; } if (self.motionManager.gyroAvailable) { self.motionManager.gyroUpdateInterval = 1.0 / 10.0; [self.motionManager startGyroUpdatesToQueue:self.queue withHandler: ^(CMGyroData *gyroData, NSError *error) { NSString *labelText; labelText = [NSString stringWithFormat: @"Gyroscope\n--------\nx: %+.2f\ny: %+.2f\nz: %+.2f", gyroData.rotationRate.x, gyroData.rotationRate.y, gyroData.rotationRate.z]; NSLog(@"%@",labelText); }]; } else { self.gyroscopeLabel.text = @"This device has no gyroscope"; } } @end 切记要导入CoreMotion.framework框架 本文转蓬莱仙羽51CTO博客,原文链接:http://blog.51cto.com/dingxiaowei/1366411,如需转载请自行联系原作者

优秀的个人博客,低调大师

ios14--购物车优化2

// // ViewController.m // 03-综合练习 // // Created by xiaomage on 15/12/28. // Copyright © 2015年 小码哥. All rights reserved. // #import "ViewController.h" @interface ViewController () // 购物车 @property (weak, nonatomic) IBOutlet UIView *shopCarView; // 添加按钮 @property (weak, nonatomic) IBOutlet UIButton *addButton; // 删除按钮 @property (weak, nonatomic) IBOutlet UIButton *removeButton; /** 数据数组 */ @property (nonatomic, strong) NSArray *dataArr; @end @implementation ViewController /** * 懒加载 1.作用: 1>用到的时候再加载 2>全局只会被加载一次 3>全局都可以使用 过程: 1.重写成员变量的get方法 2.在get方法中判断: 1>如果为空,加载数据 2>如果不为空,就直接返回数据 */ - (NSArray *)dataArr{ if (_dataArr == nil) { // 加载数据 self.dataArr = @[ @{@"name":@"单肩包", @"icon":@"danjianbao"}, @{@"name":@"钱包", @"icon":@"qianbao"}, @{@"name":@"链条包", @"icon":@"liantiaobao"}, @{@"name":@"手提包", @"icon":@"shoutibao"}, @{@"name":@"双肩包", @"icon":@"shuangjianbao"}, @{@"name":@"斜挎包", @"icon":@"xiekuabao"} ]; } return _dataArr; } // 初始化数据 - (void)viewDidLoad { [super viewDidLoad]; // NSArray<NSDictionary *> *dataArr = @[ // @{@"name":@"单肩包", @"icon":@"danjianbao"}, // @{@"name":@"钱包", @"icon":@"qianbao"}, // @{@"name":@"链条包", @"icon":@"liantiaobao"}, // @{@"name":@"手提包", @"icon":@"shoutibao"}, // @{@"name":@"双肩包", @"icon":@"shuangjianbao"}, // @{@"name":@"斜挎包", @"icon":@"xiekuabao"} // ]; // self.dataArr = dataArr; } /** * 添加到购物车 * * @param button 按钮 */ - (IBAction)add:(UIButton *)button { /***********************1.定义一些常量*****************************/ // 1.总列数 NSInteger allCols = 3; // 2.商品的宽度 和 高度 CGFloat width = 80; CGFloat height = 100; // 3.求出水平间距 和 垂直间距 CGFloat hMargin = (self.shopCarView.frame.size.width - allCols * width) / (allCols -1); CGFloat vMargin = (self.shopCarView.frame.size.height - 2 * height) / 1; // 4. 设置索引 NSInteger index = self.shopCarView.subviews.count; // 5.求出x值 CGFloat x = (hMargin + width) * (index % allCols); CGFloat y = (vMargin + height) * (index / allCols); /***********************2.创建一个商品*****************************/ // 1.创建商品的view UIView *shopView = [[UIView alloc] init]; // 2.设置frame shopView.frame = CGRectMake(x, y, width, height); // 3.设置背景颜色 shopView.backgroundColor = [UIColor greenColor]; // 4.添加到购物车 [self.shopCarView addSubview:shopView]; // 5.创建商品的UIImageView对象 UIImageView *iconView = [[UIImageView alloc] init]; iconView.frame = CGRectMake(0, 0, width, width); iconView.backgroundColor = [UIColor blueColor]; [shopView addSubview:iconView]; // 6.创建商品标题对象 UILabel *titleLabel = [[UILabel alloc] init]; titleLabel.frame = CGRectMake(0, width, width, height - width); titleLabel.backgroundColor = [UIColor yellowColor]; titleLabel.textAlignment = NSTextAlignmentCenter; // 居中 [shopView addSubview:titleLabel]; /***********************3.设置数据*****************************/ // 方式四 (数组 + 字典) /* NSArray<NSDictionary *> *dataArr = @[ @{@"name":@"单肩包", @"icon":@"danjianbao"}, @{@"name":@"钱包", @"icon":@"qianbao"}, @{@"name":@"链条包", @"icon":@"liantiaobao"}, @{@"name":@"手提包", @"icon":@"shoutibao"}, @{@"name":@"双肩包", @"icon":@"shuangjianbao"}, @{@"name":@"斜挎包", @"icon":@"xiekuabao"} ]; */ // 懒加载 /* if (self.dataArr == nil) { self.dataArr = @[ @{@"name":@"单肩包", @"icon":@"danjianbao"}, @{@"name":@"钱包", @"icon":@"qianbao"}, @{@"name":@"链条包", @"icon":@"liantiaobao"}, @{@"name":@"手提包", @"icon":@"shoutibao"}, @{@"name":@"双肩包", @"icon":@"shuangjianbao"}, @{@"name":@"斜挎包", @"icon":@"xiekuabao"} ]; } */ // 设置数据 NSDictionary *dict = self.dataArr[index];//调用get方法 iconView.image = [UIImage imageNamed:dict[@"icon"]]; titleLabel.text = dict[@"name"]; /***********************4.设置按钮的状态*****************************/ button.enabled = (index != 5); // 5.设置删除按钮的状态 self.removeButton.enabled = YES; } /** * 从购物车中删除 * * @param button 按钮 */ - (IBAction)remove:(UIButton *)button { // 1. 删除最后一个商品 UIView *lastShopView = [self.shopCarView.subviews lastObject]; [lastShopView removeFromSuperview]; // 3. 设置添加按钮的状态 self.addButton.enabled = YES; // 4. 设置删除按钮的状态 /* if (self.shopCarView.subviews.count == 0) { self.removeButton.enabled = NO; } */ self.removeButton.enabled = (self.shopCarView.subviews.count != 0); } @end 本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7449679.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

学习ios【1】Objective-C 基本语法

一 了解一下,找参考资料 1.看书学习object-c语法,第一本看的是《objective-c程序设计》。 2.官网:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html 二 定义类 1. 格式 object-c中定义类的方式和c#不同,它分为两个部分,一般放在两个独立的文件中: ①在@interface部分声明类,文件格式.h; ②在@implementation部分实现类,文件格式.m。 2.@interface 部分 Fraction.h #import <Foundation/Foundation.h> @interface Fraction: NSObject-(void)setAge:(int)age; -(int)getAge; @end 以上代码有几点说明: ①NSObject是默认的父类; ②方法前面的负号(-)表示这是一个实例方法;如果是正号(+)表示这是一个类方法。 3. @implementation 部分 Fraction.m #import "Fraction.h" @implementation Fraction { int _age; } -(void)setAge:(int)age { _age=age; } -(int)getAge { return _age; } @end 4.调用 注意:@autoreleasepool引入了自动计数处理内存释放问题;看一下对象初始化和方法调用的格式。 main.m #import <Foundation/Foundation.h> #import "Fraction.h" int main(int argc, const char * argv[]) {@autoreleasepool{ //对象初始化 Fraction *fraction=[Fraction alloc]; fraction=[fraction init]; //调用方法 [fraction setAge:100]; int age=[fraction getAge]; //打印结果 NSLog(@"the age is %i",age); } } 三 基本数据类型 1. 基本类型 object-c的几种基本数据类型: int ,float,double,char 2.float类型 NSLog转换字符为 %f或者%g NSLog(@"The float result is %f",f);//The float result is 1.230000 NSLog(@"The float result is %g",f);//The float result is 1.23 3.字符串 用@开头并且放在双引号中的字符串是NSString字符串类型。 各类型的NSLog输出转换如下: int main(int argc,const char* argv[]){ @autoreleasepool{ int a=100; NSLog(@"the integer value is%i",a); float f=1.23; NSLog(@"The float result is%f",f);//The float result is 1.230000 NSLog(@"The float result is%g",f);//The float result is 1.23 double d=1.2345; NSLog(@"The double value is%e",d);//The double value is 1.234500e+000 char c='V'; NSLog(@"The char value is%c",c);//The char value is V } return 0; } 4.id类型 id数据类型可以存储任何类型的对象。id类型是多态和动态绑定的基础。 5.布尔类型 objective-c中的布尔值是YES和NO. int main(int argv,const char * argc[]) { @autoreleasepool { for(int i=2;i<=50;i++) { bool isPrime=YES; for(int j=2;j<i;j++) { if(i%j==0) { isPrime=NO; continue; } } if(isPrime==YES) { NSLog(@"%i",i); } } } return 0; } 四 scanf和NSLog scanf :接收输入值,第一个参数始终是C风格的字符串,第二个参数用于指定用户输入的值储存在哪里; NSLog:输出结果,第一个参数始终是NSString。 int main(int argc, const char * argv[]) { @autoreleasepool { int number; NSLog(@"请输入要计算的数值?");scanf("%i",&number); int result=0; for(int i=1;i<=number;i++) { result+=i; } NSLog(@"The Triangular number of %i is %i",number,result); } return 0; } 五 类 1 合成存取方法 所谓合成存取方法,就是自动设值和取值,类似于c#中的属性。它的定义和使用步骤为: ①在 @interface 中使用 @property 标识属性; ②在 @implementation 中使用 @synthesize 指令; ③调用属性方法,可以使用传统的方括号语法,也可以使用点运算符进行属性读写。 Fraction.h #import <Foundation/Foundation.h> @interface Fraction : NSObject @propertyintnumber1,number2; -(void)print; @end Fraction.m #import "Fraction.h" @implementation Fraction @synthesizenumber1,number2; -(void)print { NSLog(@"number1 is %i,number2 is %i",number1,number2); } @end main.m #import <Foundation/Foundation.h> #import "Fraction.h" int main(int argc, const char * argv[]) { @autoreleasepool { Fraction *fraction=[Fraction alloc]; fraction=[fraction init]; //调用方式1 [fractionsetNumber1:10]; [fractionsetNumber2:20]; [fraction print]; //调用方式2 fraction.number1=30; fraction.number2=40; [fraction print]; } } 2.多个参数的方法 例如我们想同时设置上述例子Fraction中的number1和number2的值,可以使用带多个参数的方法。(说实话,第一次看到这个语法的时候尴尬症都犯了。) Fraction.h #import <Foundation/Foundation.h> @interface Fraction : NSObject @property int number1,number2; -(void)print;-(void)setNumber1:(int)n1 andNumber2:(int)n2; @end Fraction.m #import "Fraction.h" @implementation Fraction @synthesize number1,number2; -(void)print { NSLog(@"number1 is %i,number2 is %i",number1,number2); }-(void)setNumber1:(int)n1 andNumber2:(int)n2 {number1=n1;number2=n2; } @end main.m #import <Foundation/Foundation.h> #import "Fraction.h" int main(int argc, const char * argv[]) { @autoreleasepool { Fraction *fraction=[Fraction alloc]; fraction=[fraction init]; [fractionsetNumber1:50andNumber2:60]; [fraction print]; } } 3.方法带引用类型的参数 Fraction.h #import <Foundation/Foundation.h> @interface Fraction : NSObject @property int number1,number2; -(void)print; -(void)setNumber1:(int)n1 andNumber2:(int)n2; -(void)add:(Fraction*)f; @end Fraction.m #import "Fraction.h" @implementation Fraction @synthesize number1,number2; -(void)print { NSLog(@"number1 is %i,number2 is %i",number1,number2); } -(void)setNumber1:(int)n1 andNumber2:(int)n2 { number1=n1; number2=n2; }-(void)add:(Fraction*)f {number1+=f.number1;number2+=f.number2; } @end main.m #import <Foundation/Foundation.h> #import "Fraction.h" int main(int argc, const char * argv[]) { @autoreleasepool { Fraction *f1=[[Fraction alloc] init]; Fraction *f2=[[Fraction alloc] init]; [f1 setNumber1:1 andNumber2:2]; [f2 setNumber1:3 andNumber2:4]; [f1 add:f2]; [f1 print]; } } 六 继承 1. 继承 我们所定义的类都是从NSObject继承而来。 继承实例: 在这个例子中Rectangle是父类,Square是子类。 XYPoint.h #import <Foundation/Foundation.h> @interface XYPoint : NSObject @property int x,y; -(void)setX:(int)x andSetY:(int)y; @end XYPorint.m #import "XYPoint.h" @implementation XYPoint @synthesize x,y; -(void)setX:(int)xVal andSetY:(int)yVal { 在这个例子中Rectangle是父类,Square是子类 x=xVal; y=yVal; } @end 父类: Rectangle.h #import <Foundation/Foundation.h> #import "XYPoint.h" @interface Rectangle : NSObject @property int width,height; -(void)setWidth:(int)w andSetHeight:(int)h; -(int)area; -(void)setOrignal:(XYPoint *)original; -(XYPoint *)original; @end Rectangle.m #import "Rectangle.h" @implementation Rectangle { XYPoint * _original; } @synthesize width,height; -(void)setWidth:(int)w andSetHeight:(int)h { width=w; height=h; } -(int)area { return width*height; } -(int)area { return width*height; } -(void)setOrignal:(XYPoint *)p { _original=p; } -(XYPoint *)original { return _original; } @end 子类 Square.h #import <Foundation/Foundation.h> #import "Rectangle.h" @interfaceSquare :Rectangle -(void)setSide:(int)s; -(int)side; @end Square.m #import "Square.h" @implementation Square -(void)setSide:(int)s { [selfsetWidth:s andSetHeight:s]; } -(int)side { returnself.width; } @end main.m #import "Rectangle.h" #import "Square.h" int main(int argc,const char * argv[]) { @autoreleasepool { //父类 Rectangle *rectangle=[[Rectangle alloc] init]; [rectangle setWidth:5 andSetHeight:6]; NSLog(@"rectangle w=%i,h=%i,area=%i",rectangle.width,rectangle.height,[rectangle area]); //子类 Square *square=[[Square alloc] init]; [square setSide:8]; NSLog(@"square side=%i,area=%i",square.side,[square area]); } return 0; } 2.覆盖 如果子类使用和父类相同的名称定义的方法,可以覆写父类中的方法。新方法必须具有相同的返回类型,并且参数的数目与覆写方法完全一致。例如下面的例子中ClassB覆写了ClassA的initVar方法。 ClassA.h #import <Foundation/Foundation.h> @interface ClassA : NSObject { int x; } -(void)initVar; -(void)print; @end ClassA.m #import "ClassA.h" @implementation ClassA -(void)initVar { x=1; } -(void)print { NSLog(@"x=%i",x); } @end ClassB.h #import <Foundation/Foundation.h> #import "ClassA.h" @interface ClassB : ClassA -(void)initVar; @end ClassB.m @implementation ClassB -(void)initVar { x=2; } @end main.m #import "ClassB.h" int main(int argc,const char * argv[]) { @autoreleasepool { ClassB * b=[[ClassB alloc] init]; [b initVar]; [b print];//x=2 } return 0; } 七 id类型和动态绑定 1. id可以用来存储属于任何类的对象。 例如: #import "Complex" int main(int argc,const char * argv[]) { @autoreleasepool { id d1=[[Complex alloc] init]; //Complex *c1=[[Complex alloc] init]; [d1 setReal:1 andImaginary:2]; id d2=[[Comlex alloc] init]; [d2 setReal:3 andImaginary:4]; [d1 print]; NSLog(@" +"); [d2 print]; NSLog(@"-------"); id d3=[d1 add:d2]; [d3 print]; } return 0; } 注意,这里id类型的声明中不使用星号。 为了尽量在编译期间就识别到更多地错误,并且增强程序的可读性,不要养成滥用id这种通用数据类型的习惯。尽量使用静态类型和有意义的变量名来提高程序的可读性。 八 捕捉异常 @try …@catch可以捕获到程序中的异常,如下所示: int main(int argc,const char * argv[]) { @autoreleasepool { @try { ... }@catch (NSException *ex) {NSLog(@"error name:%@ ;reason:%@",[ex name],[ex reason]); }@finally { NSLog(@"done"); } return 0; } } 当出现异常时,会执行@catch代码块,参数NSException对象包含了异常的详细信息,name方法返回异常的名称,reason方法给出异常的详细信息。 九 变量和数据类型 1.自定义对象的初始化方法 在前面的例子中,我们创建对象并且初始化都是这样做的: Complex *c1=[[Complex alloc] init]; [c1 setReal:10 andImaginary:20]; 接下来我们自定义对象的初始化方法,一般也是以init开头。 Complex.h @interface Complex : NSObject @property double real,imaginary; -(void)print; -(void)setReal:(double)r andImaginary:(double) m; -(Complex*)initWithReal:(double)r andImaginary:(double) m; @end Complex.m #import "Complex.h" @implementation Complex @synthesize real,imaginary; -(void)print { NSLog(@"%g + %gi",real,imaginary); } -(void)setReal:(double)r andImaginary:(double)m { real=r; imaginary=m; } -(Complex*)initWithReal:(double)r andImaginary:(double)m {self=[superinit];if(self) { [selfsetReal:randImaginary:m]; }returnself; } @end main.m #import "Complex.h" int main(int argc,const char * argv[]) { @autoreleasepool { Complex *c=[[Complex alloc] initWithReal:10 andImaginary:20]; [c print]; } return 0; } 2.静态变量 静态变量定义在所有方法之外,使用static修饰符,它属于类,而不属于类对象。例如在下面的例子中,使用gCount变量记录allocC调用次数。 Complex.h #import <Foundation/Foundation.h> @interface Complex : NSObject @property double real,imaginary; ... +(Complex *)allocC; +(int)count; @end Complex.m #import "Complex.h"staticintgCount=0; @implementation Complex ... +(Complex *)allocC { gCount++; return [Complex alloc]; } +(int)count { return gCount; } @end main.m #import "Complex.h" int main(int argc,const char * arg[]) { @autoreleasepool { NSLog(@"count=%i",[Complex count]);//0 Complex *c=[[Complex allocC] init]; Complex *c1=[[Complex allocC] init]; Complex *c2=[[Complex allocC] init]; NSLog(@"count=%i",[Complex count]);//3 } return 0; } 十 分类和协议 1.分类 通过分类可以很简单地向现有类添加方法,功能类似于C#的扩展方法。格式为: @interface Complex(MathOps) 例如: ①现有Complex.h定义: #import <Foundation/Foundation.h> @interface Complex : NSObject @property double real,imaginary; -(void)print; -(void)setReal:(double)r andImaginary:(double) m; @end Complex.m #import "Complex.h" //static int gCount=0; @implementation Complex @synthesize real,imaginary; -(void)print { NSLog(@"%g + %gi",real,imaginary); } -(void)setReal:(double)r andImaginary:(double)m { real=r; imaginary=m; } @end ②现在想扩展Complex类,如下: Complex+MathOps.h #import <Foundation/Foundation.h> #import "Complex.h" @interface Complex(MathOps) -(Complex *)add:(Complex *)c; @end Complex+MathOps.m #import "Complex+MathOps.h" @implementation Complex(MathOps) -(Complex *)add:(Complex *)c { Complex *result=[[Complex alloc] init]; result.real=self.real+c.real; result.imaginary=self.imaginary+c.imaginary; return result; } @end main.m调用: #import "Complex.h" #import "Complex+MathOps.h" int main(int argc,const char * argv[]) { @autoreleasepool { Complex *c1=[[Complex alloc] init]; [c1 setReal:1 andImaginary:2]; Complex *c2=[[Complex alloc] init]; [c2 setReal:3 andImaginary:4]; Complex *c3=[c1 add:c2]; [c3 print];//4 + 6i } return 0; } 这样我们就为原有的Complex类新增了add方法。 2.协议 protocol定义一组方法,它是不属于具体某个类的,可以被任意类实现,类似于C#中的接口interface。 ①定义protocal 使用@protocol指令,后面跟上协议名称,以@end指令结束。 例如: MathProtocol.h #import <Foundation/Foundation.h> @protocol MathProtocol -(id)add:(id)v; @optional -(id)subscribe:(id)v; @end 其中@optional指令表示其后面的方法是可选的。 ②实现protocol 在@interface行使用尖括号<>,其中加上协议的名称,然后在.m文件中实现协议中的方法即可。 Complex11.h #import <Foundation/Foundation.h> #import "MathProtocol.h" @interface Complex11 : NSObject<MathProtocol> @property int real,imaginary; -(void)setReal:(int)r andImaginary:(int)m; @end Complex11.m #import "Complex11.h" @implementation Complex11 @synthesize real,imaginary; -(void)setReal:(int)r andImaginary:(int)m { real=r; imaginary=m; } -(Complex11 *)add:(Complex11 *)v { Complex11 *result=[[Complex11 alloc] init]; result.real=self.real+v.real; result.imaginary=self.imaginary+v.imaginary; return result; } @end main.m #import "Complex11.h" int main(int argc,const char * argv[]) { @autoreleasepool { Complex11 *c=[[Complex11 alloc] init]; [c setReal:1 andImaginary:2]; Complex11 *c2=[[Complex11 alloc] init]; [c2 setReal:3 andImaginary:4]; Complex11 *result=[c add:c2]; NSLog(@"%i +%ii",result.real,result.imaginary); //检查是否遵循某项协议 bool isprotocol=[c conformsToProtocol:@protocol(MathProtocal)]; if(isprotocol==YES){ NSLog(@"c confirm protocol MathProtocol"); } } return 0; } 要想判断一个对象是否遵守某项协议,可以使用confirmsToProtocol方法。 本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/5391258.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

疯狂ios之疯狂打飞机游戏(3)

13.14.7添加敌机 游戏当中怎么能少了千军万马的敌人呢?现在,我们来添加一些敌机,大量的敌机将从屏幕上方随机出现,并以随机的速度向下俯冲。这些敌机暂时不会发射子弹,之后读者可以自己添加该功能。具体步骤如下。 自定义一个FKSprite类,继承自CCSprite,因为创建的敌机玩家会发射子弹去消灭,为了增加游戏的趣味性和难度,需要加入敌机的生命值、血条和爆炸效果等特效。在FKSprite类中定义了相关变量用于存储数据。实现代码如下。 程序清单:codes/13/13.14/AirfightGame/AirfightGame/FKSprite.h @interfaceFKSprite : CCSprite { } //精灵的生命值 @property int lifeValue; //精灵的名称 @property NSString* name; //敌机的血条 @property CCProgressTimer* enemyPlaneHP; //血条的更新量 @property float HPInterval; @end 打开HelloWorldLayer.m文件,添加两个变量,实现代码如下。 //敌机数组 CCArray* enemyPlaneArray; //游戏帧计数器 NSInteger count; 在私有分类中添加两个和敌机相关的方法,实现代码如下。 //更新敌机 -(void) updateEnemySprite:(ccTime)delta; //敌机离开屏幕删除 -(void) removeEnemySprite:(ccTime)delta; updateEnemySprite:用于控制敌机的创建、俯冲。实现代码如下。 程序清单:codes/13/13.14/AirfightGame/AirfightGame/HelloWorldLayer.m -(void) updateEnemySprite:(ccTime)delta{ //控制count为100的倍数时添加一架敌机 if (count % 30 == 0) { // FKSprite精灵对象继承自CCSprite,增加了生命值 FKSprite* enemyPlaneSprite; //根据rand随机数添加不同的敌机 int rand = arc4random() % 2; //使用随机数来设置敌机的X坐标 int randX = arc4random() % (screenWidth - 40) + 20; switch(rand) { case 0: //创建代表敌机 enemyPlaneSprite = [FKSprite spriteWithSpriteFrameName:@"e0.png"]; enemyPlaneSprite.position = ccp(randX,480+enemyPlaneSprite.contentSize.height); enemyPlaneSprite.name = @"e0"; enemyPlaneSprite.lifeValue = 1; break; case 1: //创建代表敌机 enemyPlaneSprite = [FKSprite spriteWithSpriteFrameName:@"e2.png"]; enemyPlaneSprite.position = ccp(randX,480+enemyPlaneSprite.contentSize.height); enemyPlaneSprite.name = @"e2"; enemyPlaneSprite.lifeValue = 1; break; } //获取随机时间(敌机俯冲的时间) float durationTime = arc4random() %2 + 2; //敌机俯冲 id moveBy = [CCMoveBy actionWithDuration:durationTime position:ccp(0,-enemyPlaneSprite.position.y-enemyPlaneSprite.contentSize.height)]; [enemyPlaneSprite runAction:moveBy]; //将敌机精灵添加到敌机数组中 [enemyPlaneArray addObject:enemyPlaneSprite]; //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; [batchNode addChild:enemyPlaneSprite z:4]; }else{ if (count % 200 == 0) { int randX = arc4random() % (screenWidth - 40) + 20; // FKSprite精灵对象继承自CCSprite,增加了生命值 FKSprite* enemyPlaneSprite; //创建代表敌机 enemyPlaneSprite = [FKSprite spriteWithSpriteFrameName:@"e1.png"]; enemyPlaneSprite.position = ccp(randX,480+enemyPlaneSprite.contentSize.height); enemyPlaneSprite.name = @"e1"; enemyPlaneSprite.lifeValue = 10; //获取随机时间(敌机掉落的时间) float durationTime = arc4random() %2 + 2; //敌机俯冲 id moveBy = [CCMoveBy actionWithDuration:durationTime position:ccp(0,-enemyPlaneSprite.position.y-enemyPlaneSprite.contentSize.height)]; [enemyPlaneSprite runAction:moveBy]; //将敌机精灵添加到敌机数组中 [enemyPlaneArray addObject:enemyPlaneSprite]; //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; [batchNode addChild:enemyPlaneSprite z:4]; //创建一个进度条精灵 CCSprite* barSprite = [CCSprite spriteWithFile:@"planeHP.png"]; //初始化一个CCProgressTimer对象 CCProgressTimer* enemyPlaneHP = [CCProgressTimer progressWithSprite:barSprite]; // setPercentage:0.0f,表示并未加载任何资源,表现在画面上就是什么也看不见 [enemyPlaneHP setPercentage:0.0f]; //由于图片大小关系,把scale设置成0.15,即缩小一半 enemyPlaneHP.scale = 0.15; enemyPlaneHP.midpoint = ccp(0,0.5); enemyPlaneHP.barChangeRate = ccp(1, 0); enemyPlaneHP.type = kCCProgressTimerTypeBar; enemyPlaneHP.percentage = 100; CGPoint pos = enemyPlaneSprite.position; enemyPlaneHP.position = ccp(pos.x, pos.y+32); [self addChild:enemyPlaneHP]; id moveBy2 = [CCMoveBy actionWithDuration:durationTime position:ccp(0,-enemyPlaneSprite.position.y-enemyPlaneSprite.contentSize.height)]; [enemyPlaneHP runAction:moveBy2]; enemyPlaneSprite.enemyPlaneHP = enemyPlaneHP; enemyPlaneSprite.HPInterval = 100.0 / (float)enemyPlaneSprite.lifeValue; } } } 这段代码有点长,接下来为大家详细解释。 首先,游戏中出现的小敌机有3种,通过count变量来控制敌机出现的频率(count变量在update方法中自增)。 当count%30==0时,随机创建两种小飞机,对应e0.png和e2.png图片,设置生命值为1。接下来获取一个随机俯冲时间,根据该时间创建一个moveBy动作,让飞机执行moveBy动作俯冲。同时将敌机精灵添加到敌机数组和精灵表单当中。 当count%200==0时,创建一种小飞碟,对应e1.png图片,设置生命值为10。接下来获取一个随机俯冲时间,根据该时间创建一个moveBy动作,让飞机执行moveBy动作俯冲。同时将敌机精灵添加到敌机数组和精灵表单当中。之后使用前面用过的CCProgressTimer类创建了一个血条,游戏中血条会随着敌机被玩家飞机的子弹打中而减少,从而实现非常炫的射击效果。 removeEnemySprite的作用是当敌机已经移出屏幕外时删除敌机精灵。实现代码如下。 程序清单:codes/13/13.14/AirfightGame/ AirfightGame/HelloWorldLayer.m -(void) removeEnemySprite:(ccTime)delta{ //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; //定义循环变量 CCSprite* enemyPlaneSprite; //遍历所有的敌机精灵 CCARRAY_FOREACH(enemyPlaneArray, enemyPlaneSprite){ //如果敌机已经移出屏幕外,则删除敌机精灵 if (enemyPlaneSprite.position.y <= -enemyPlaneSprite.contentSize.height) { //从精灵表单中删除该敌机精灵 [batchNode removeChild:enemyPlaneSprite cleanup:YES]; //从敌机数组中删除该敌机精灵 [enemyPlaneArray removeObject:enemyPlaneSprite]; } } } removeEnemySprite:比较简单,首先调用getChildByTag:方法获取精灵表单,然后遍历敌机数组,判断敌机的y轴若超出屏幕范围,则从精灵表单和敌机数组中删除敌机精灵。 找到onEnter方法,在⑤部分代码后初始化敌机数组,实现代码如下(程序清单同上)。 enemyPlaneArray = [[CCArray alloc] init]; 修改update方法,实现代码如下(程序清单同上)。 -(void) update:(ccTime)delta{ count++; [self updateBackground:delta]; [self updateEnemySprite:delta]; [self removeEnemySprite:delta]; } 再次编译并运行游戏,大量的敌机会随机出现,并向屏幕下方俯冲。模拟器显示效果如图13.63所示。 13.14.8玩家飞机添加子弹并射击 现在,大量的敌机向玩家飞机俯冲过来,不用多说,给玩家飞机添加子弹射击功能打爆它们。这里我们设计成子弹自动发射,并且子弹是无限的,这样玩家就只需要专心控制飞机的飞行就可以了。具体步骤如下。 打开HelloWorldLayer.m文件,添加变量,实现代码如下(程序清单同上)。 //代表子弹精灵数组 CCArray* bulletArray; 在私有分类中添加3个和敌机相关的方法,实现代码如下(程序清单同上)。 //更新子弹 -(void) updateShooting:(ccTime)delta; //子弹离开屏幕,删除 -(void) removeBulletSprite:(ccTime)delta; //碰撞检测 -(void) collisionDetection:(ccTime)delta; updateShooting:方法用于不断发射子弹。实现代码如下(程序清单同上)。 -(void) updateShooting:(ccTime)delta{ //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; //飞机精灵坐标 CGPoint pos = planeSprite.position; //控制count为8的倍数时发射一颗子弹 if(count % 8 == 0) { //创建代表子弹的精灵 CCSprite* bulletSprite = [CCSprite spriteWithSpriteFrameName:@"bullet.png"]; //设置子弹坐标 CGPoint bulletPos = ccp(pos.x, pos.y + planeSprite.contentSize.height/2 + bulletSprite.contentSize.height); bulletSprite.position = bulletPos; //子弹移动时间为0.4秒,移动距离为屏幕高度-子弹的y轴 id moveBy = [CCMoveBy actionWithDuration:0.4f position:ccp(0, screenHeight-bulletPos.y)]; [bulletSprite runAction:moveBy]; //将子弹精灵添加到精灵表单中 [batchNode addChild:bulletSprite z:4]; //将子弹精灵添加到子弹精灵数组中 [bulletArray addObject:bulletSprite]; } } updateShooting:方法并不复杂,首先获取精灵表单,然后获取玩家飞机的坐标位置,当count%8==0时创建一颗子弹精灵,并执行moveBy动作达到发射子弹的效果,最后将子弹精灵添加到精灵表单和子弹精灵数组当中。 removeBulletSprite:方法的作用是当子弹精灵已经移出屏幕外时删除子弹精灵。实现代码如下(程序清单同上)。 -(void) removeBulletSprite:(ccTime)delta{ //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; CCSprite* bulletSprite; //遍历所有的子弹 CCARRAY_FOREACH(bulletArray, bulletSprite){ //如果子弹已经移出屏幕外,则删除子弹 if (bulletSprite.position.y >=screenHeight){ //从精灵表单中删除该子弹精灵 [batchNode removeChild:bulletSprite cleanup:YES]; //从子弹数组中删除该子弹精灵 [bulletArray removeObject:bulletSprite]; } } } removeBulletSprite:方法也比较简单,首先调用getChildByTag:方法获取精灵表单,然后遍历子弹数组,判断子弹的y轴若超出屏幕范围,则从子弹表单和子弹数组中删除子弹精灵。 collisionDetection:是检查玩家飞机和敌机碰撞或者子弹和敌机碰撞的方法。实现代码如下(程序清单同上)。 -(void) collisionDetection:(ccTime)dt{ //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; //定义循环变量 FKSprite* enemyPlaneSprite; CCSprite* bulletSprite; //遍历敌机数组 CCARRAY_FOREACH(enemyPlaneArray, enemyPlaneSprite){ //玩家飞机和敌机发生碰撞 if(CGRectIntersectsRect(planeSprite.boundingBox,enemyPlaneSprite.boundingBox)){ //播放爆炸动画 [self bombAnimate:@"blast" :enemyPlaneSprite.position ]; //删除敌机精灵 [enemyPlaneArray removeObject:enemyPlaneSprite]; [batchNode removeChild:enemyPlaneSprite cleanup:YES]; [planeSprite stopAllActions]; //删除玩家精灵 [batchNode removeChild:planeSprite cleanup:YES]; [self gameOver:@"游戏结束!"]; } //遍历子弹数组 CCARRAY_FOREACH(bulletArray, bulletSprite){ //如果敌机与子弹发生碰撞 if(CGRectIntersectsRect(enemyPlaneSprite.boundingBox, bulletSprite.boundingBox)){ //播放子弹音效 [[SimpleAudioEngine sharedEngine] playEffect:@"bullet.mp3"]; //删除子弹精灵 [bulletArray removeObject:bulletSprite]; [batchNode removeChild:bulletSprite cleanup:YES]; //敌机生命值减1 enemyPlaneSprite.lifeValue--; //血条减少 if (enemyPlaneSprite.enemyPlaneHP != nil) { enemyPlaneSprite.enemyPlaneHP.percentage = enemyPlaneSprite.HPInterval * enemyPlaneSprite.lifeValue; } //判断敌机的生命值 if (enemyPlaneSprite.lifeValue <= 0) { //删除敌机精灵 [enemyPlaneArray removeObject:enemyPlaneSprite]; [batchNode removeChild:enemyPlaneSprite cleanup:YES]; //播放爆炸动画 [self bombAnimate:@"blast" :enemyPlaneSprite.position ]; //播放爆炸音效 [[SimpleAudioEngine sharedEngine] playEffect:@"b0.mp3"]; } break; } } } } collisionDetection:方法首先调用getChildByTag:方法获取精灵表单,然后循环遍历敌机数组。CGRectIntersectsRect(rect 1.feet 2)函数可以判断矩形结构是否交叉,两个矩形对象是否重叠,常用来检测两个图标是否发生碰撞。CCNode有一个属性boundingBox,会返回精灵的边界框。使用这个属性比自己计算要好,因为这样做更简单,同时也考虑了精灵的变形。通过CGRectIntersectsRect(rect 1.feet 2)函数判断玩家飞机和敌机是否发生碰撞,如果发生碰撞,则播放一段爆炸动画,然后从敌机数组和精灵表单中删除敌机精灵,再从精灵表单中删除玩家飞机精灵,最后调用gameOver:方法结束游戏。 如果玩家飞机和敌机没有发生碰撞,则不循环遍历子弹数组,判断子弹和敌机是否发生碰撞,如果发生碰撞,则播放子弹音效,删除子弹精灵,将敌机生命值减去1;如果敌机有血条,则更新血条(小飞碟生命值为10,有血条)。接下来判断敌机的生命值,如果敌机生命值为0,则从敌机数组和精灵表单中删除敌机精灵,播放爆炸动画和爆炸音效。 在私有分类中添加两个方法,实现代码如下(程序清单同上)。 //播放爆炸动画 -(void) bombAnimate:(NSString*) name : (CGPoint) position; //游戏结束 -(void) gameOver:(NSString*) labelString; bombAnimate: name:方法用于播放爆炸动画。实现代码如下(程序清单同上)。 -(void) bombAnimate:(NSString*) name : (CGPoint) position { NSString* bombName = [NSString stringWithFormat:@"%@0.png",name]; float delay = 0.08f; CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; CCSprite* blastSprite = [CCSprite spriteWithSpriteFrameName:bombName]; blastSprite.position = position; //获得动画帧 CCAnimation* blastAnimation = [self getAnimationByName:name delay:delay animNum:4]; //组合动作:1.播放动画2.删除动画精灵对象 id action = [CCSequence actions: [CCAnimate actionWithAnimation:blastAnimation], [CCCallBlock actionWithBlock:^() { [batchNode removeChild:blastSprite cleanup:YES]; }],nil]; [blastSprite runAction:action]; [batchNode addChild:blastSprite z:4]; } bombAnimate: name:方法接收传进来的爆炸效果名称,获取爆炸动画帧,先播放动画,动画播放完毕后删除动画。 gameOver:方法用于游戏结束时清除精灵对象并提示游戏信息。实现代码如下(程序清单同上)。 -(void) gameOver:(NSString*) labelString{ //停止所有动作 [self unscheduleUpdate]; //游戏结束 CCMenuItemFont* gameItem = [CCMenuItemFont itemWithString:labelString target:self selector:@selector(onRestartGame:)]; gameItem.position=ccp(screenWidth/2, screenHeight/2); CCMenu* menu = [CCMenu menuWithItems:gameItem, nil]; menu.position = CGPointZero; [self addChild:menu]; } 找到onEnter方法,在⑤部分代码后初始化子弹数组,实现代码如下。 bulletArray = [[CCArray alloc] init]; 修改update方法,实现代码如下(程序清单同上)。 -(void) update:(ccTime)delta{ count++; [self updateBackground:delta]; [self updateEnemySprite:delta]; [self removeEnemySprite:delta]; [self updateShooting:delta]; [self removeBulletSprite:delta]; self collisionDetection:delta]; } 再次编译并运行游戏,大量的敌机会随机出现,并向屏幕下方俯冲,控制玩家飞机发射子弹,子弹击中敌机显示爆炸效果。模拟器显示效果如图13.64所示。 13.14.9添加背景音乐 有了音效,有了爆炸效果,没有背景音乐好像缺少点热血澎湃的游戏感觉,让我们马上加入背景音乐吧。 找到onEnter方法,在游戏的主循环代码之前添加背景音乐播放功能,实现代码如下(程序清单同上)。 [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"s3.wav" loop:YES]; [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:0.5]; 再次编译并运行游戏,开始游戏时就可以听见令人热血澎湃的背景音乐了。读者可以按照13.13.2节的内容为游戏增加声音设置功能选项,包括声音开关、声音大小调节等,这里不再赘述。 本文转自fkJava李刚 51CTO博客,原文链接:http://blog.51cto.com/javaligang/1400891,如需转载请自行联系原作者

优秀的个人博客,低调大师

疯狂ios之疯狂打飞机游戏(4)

13.14.10添加游戏积分统计 现在,我们来给玩家加入游戏积分统计功能。步骤如下。 打开HelloWorldLayer.m文件,添加变量,实现代码如下(程序清单同上)。 //分数值标签 CCLabelTTF* scoreLabel; //分数 int scoreValue; 找到onEnter方法,在初始化子弹和敌机数组之后初始化分数值标签和分数,实现代码如下。 //初始化分数标签 scoreLabel = [CCLabelTTF labelWithString:@"00" fontName:@"Arial" fontSize:20]; scoreLabel.position = ccp(60, screenHeight-20); [self addChild:scoreLabel]; //初始化分数值 scoreValue = 0; 修改检查碰撞方法collisionDetection:,当敌机生命值小于0时,增加计分算法,小飞机每个计分100,小飞碟每个计分500,实现代码如下(程序清单同上)。 if (enemyPlaneSprite.lifeValue <= 0) { //删除敌机精灵 [enemyPlaneArray removeObject:enemyPlaneSprite]; [batchNode removeChild:enemyPlaneSprite cleanup:YES]; //播放爆炸动画 [self bombAnimate:@"blast" :enemyPlaneSprite.position ]; //播放爆炸音效 [[SimpleAudioEngine sharedEngine] playEffect:@"b0.mp3"]; if ([enemyPlaneSprite.name isEqualToString:@"e1"]) scoreValue += 500; else scoreValue += 100; } 在私有分类中添加一个根据分数值实时更新相应的Label的方法,实现代码如下(程序清单同上)。 -(void) updateHUD:(ccTime)delta; updateHUD:方法实时更新生命值和分数值,地图、分数、血条、时间进度条和技能条等都是HUD(Head-UpDisplay)。实现代码如下(程序清单同上)。 -(void) updateHUD:(ccTime)delta{ [scoreLabel setString:[NSString stringWithFormat:@"%i",scoreValue]]; } 修改update方法,实现代码如下(程序清单同上)。 -(void) update:(ccTime)delta{ count++; [self updateBackground:delta]; [self updateEnemySprite:delta]; [self removeEnemySprite:delta]; [self updateShooting:delta]; [self removeBulletSprite:delta]; self collisionDetection:delta]; [self updateHUD:delta]; } 再次编译并运行游戏,控制玩家飞机发射子弹,子弹击中敌机,左上角的分数标签不断统计玩家得分。模拟器显示效果如图13.65所示。 图13.65统计积分效果 13.14.11添加游戏大Boss 到现在为止,一个基本的打飞机游戏已经快完成了,让我们再给它添加一个大Boss,增加一点游戏的趣味性和难度吧!增加大Boss的具体步骤如下。 打开HelloWorldLayer.m文件,添加变量,实现代码如下(程序清单同上)。 FKSprite* bossSprite; // Boss子弹精灵数组 CCArray* bossBulletArray; //是否启动Boss和Boss是否发射子弹 BOOL isStartBoss,isMoveBoss,isShootingBoss,isTemp; 在私有分类中添加3个方法,实现代码如下(程序清单同上)。 // Boss出动 -(void) startBossSprite:(ccTime)delta; // Boss在屏幕上不规则移动 -(void) moveBossSprite:(ccTime)delta; // Boss更新子弹 -(void) updateBossShooting:(ccTime)delta; startBossSprite:方法用于启动Boss。实现代码如下(程序清单同上)。 -(void) startBossSprite:(ccTime)delta{ if(isStartBoss && !isMoveBoss && !isTemp ){ isTemp = YES; CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag: kTagBatchNode]; FKSprite* enemyPlaneSprite; //删除所有敌机 CCARRAY_FOREACH(enemyPlaneArray, enemyPlaneSprite){ [batchNode removeChild:enemyPlaneSprite cleanup:YES]; } [enemyPlaneArray removeAllObjects]; // Boss出动 bossSprite= [FKSprite spriteWithSpriteFrameName:@"e-10.png"]; bossSprite.position=ccp(screenWidth/2, screenHeight+bossSprite.contentSize.height); bossSprite.name = @"boss"; bossSprite.lifeValue = 600; //创建一个进度条精灵 CCSprite* barSprite = [CCSprite spriteWithFile:@"planeHP.png"]; //初始化一个Boss血条对象 bossSprite.enemyPlaneHP = [CCProgressTimer progressWithSprite:barSprite]; // setPercentage:0.0f,表示并未加载任何资源,表现在画面上就是什么也看不见 [bossSprite.enemyPlaneHP setPercentage:0.0f]; //由于图片大小关系,把scale设置成0.5,即缩小一半 bossSprite.enemyPlaneHP.scale = 0.25; bossSprite.enemyPlaneHP.midpoint = ccp(0,0.5); bossSprite.enemyPlaneHP.barChangeRate = ccp(1, 0); bossSprite.enemyPlaneHP.type = kCCProgressTimerTypeBar; bossSprite.enemyPlaneHP.percentage = 100; [bossSprite.enemyPlaneHP setPosition:ccp(screenWidth/2, screenHeight/2)]; bossSprite.enemyPlaneHP.visible = NO; [self addChild:bossSprite.enemyPlaneHP]; //血条更新量,100/10=10 bossSprite.HPInterval = 100.0 / (float)bossSprite.lifeValue; //将Boss精灵添加到敌机数组 [enemyPlaneArray addObject:bossSprite]; [batchNode addChild:bossSprite z:4]; // Boss移动到屏幕上方 id moveTo = [CCMoveTo actionWithDuration:2 position:ccp(screenWidth/2, screenHeight-bossSprite.contentSize.height-20)]; id action = [CCSequence actions:moveTo,[CCCallBlock actionWithBlock:^(){ isMoveBoss = YES; }], nil] ; [bossSprite runAction:action]; //初始化Boss子弹数组 bossBulletArray = [[CCArray alloc] init]; } } startBossSprite:方法首先判断isStartBoss是否为“YES”(默认设置为“NO”,当玩家达到10000分时会将该值改为“YES”,则Boss启动),如果是,则先获取精灵表单,循环遍历敌机数组,从精灵表单中删除敌机,再从敌机数组中删除敌机(如果玩家是高手,希望玩到高难度的打飞机游戏,则可以不执行这段代码,游戏就会变成Boss和大量的小敌机轮番轰炸玩家)。接下来,创建一个Boss精灵,设置名称为“Boss”,生命值为600,为Boss创建一个血条,并计算血条比率。然后将Boss添加到敌机数组和精灵表单中。最后,执行一个moveBy动作,实际效果是Boss缓缓移动到屏幕上方,再将isMoveBoss设置为“YES”(Boss开始不规则动作)。记得初始化Boss子弹数组。 moveBossSprite:方法用于Boss启动后在屏幕上方做不规则运动。实现代码如下(程序清单同上)。 -(void) moveBossSprite:(ccTime)delta{ if(isMoveBoss && !isShootingBoss){ isShootingBoss = YES; //不停地在屏幕上方左右移动 id moveToLift = [CCMoveTo actionWithDuration:3 position:ccp(screenWidth-bossSprite.contentSize.width/2, screenHeight-bossSprite.contentSize.height-20)]; id moveRight = [CCMoveTo actionWithDuration:3 position:ccp(0+bossSprite.contentSize.width/2, screenHeight-bossSprite.contentSize.height-20)]; id delay = [CCDelayTime actionWithDuration:2]; id sequence = [CCSequence actions:delay,moveToLift,moveRight, nil]; //注意:CCSequence中不能包含这个反复的动作。 id repeat = [CCRepeatForever actionWithAction:sequence]; [bossSprite runAction:repeat]; } } moveBossSprite:方法首先判断isMoveBoss是否为“YES”,如果是,则说明Boss精灵已经启动,开始做不规则运动,并且设置isShootingBoss = YES,表示Boss可以发射子弹攻击玩家精灵。 updateBossShooting:方法用于Boss开始发射子弹。实现代码如下(程序清单同上)。 -(void) updateBossShooting:(ccTime)delta{ if (isShootingBoss) { // Boss精灵坐标 CGPoint pos = bossSprite.position; // Boss血条显示坐标位置 bossSprite.enemyPlaneHP.position = ccp(pos.x, pos.y+55); if (!bossSprite.enemyPlaneHP.visible) { bossSprite.enemyPlaneHP.visible = YES; } //获得精灵表单 CCSpriteBatchNode *batchNode = (CCSpriteBatchNode*)[self getChildByTag:kTagBatchNode]; if(count % 80 == 0) { //创建代表子弹的精灵 CCSprite* bossBulletSprite = [CCSprite spriteWithSpriteFrameName:@"bullet1.png"]; //设置子弹坐标 CGPoint bulletPos = ccp(pos.x, pos.y - bossSprite.contentSize.height/2); bossBulletSprite.position = bulletPos; //子弹精灵可见 bossBulletSprite.visible = YES; //子弹移动时间为0.5秒,移动距离为屏幕高度-子弹的y轴 id moveBy=[CCMoveBy actionWithDuration:2.0f position:ccp(0,-screenHeight-bulletPos.y)]; [bossBulletSprite runAction:moveBy]; //添加到Boss子弹数组中 [bossBulletArray addObject:bossBulletSprite]; //将子弹精灵添加到精灵表单中 [batchNode addChild:bossBulletSprite z:4]; } } } updateBossShooting:首先判断isShootingBoss是否为“YES”,如果是,则设置Boss血条的坐标位置,并显示Boss血条。当count % 80 == 0时,发射Boss子弹,同时将Boss子弹添加到Boss子弹数组和精灵表单中。 修改collisionDetection:方法,重新判断玩家得分,并在爆炸效果之后添加代码,当玩家积分达到10000时,启动Boss。实现代码如下(程序清单同上)。 if ([enemyPlaneSprite.name isEqualToString:@"boss"]) { //播放爆炸动画 [self bombAnimate:@"bomb" :enemyPlaneSprite.position ]; //播放爆炸音效 [[SimpleAudioEngine sharedEngine] playEffect:@"b1.mp3"]; scoreValue += 5000; //游戏胜利 [self gameOver:@"游戏胜利!"]; }else{ //播放爆炸动画 [self bombAnimate:@"blast" :enemyPlaneSprite.position ]; //播放爆炸音效 [[SimpleAudioEngine sharedEngine] playEffect:@"b0.mp3"]; if ([enemyPlaneSprite.name isEqualToString:@"e1"]) scoreValue += 500; else scoreValue += 100; } // 10000分大Boss出动 if (scoreValue >= 10000) { isStartBoss = YES; break; } } 循环遍历完子弹数组之后,再添加遍历Boss子弹数组的代码,判断Boss子弹是否击中玩家飞机。实现代码如下(程序清单同上)。 //判断Boss的子弹和玩家飞机的碰撞 if (isShootingBoss) { CCSprite* bossBulletSprite; CCARRAY_FOREACH(bossBulletArray, bossBulletSprite){ if(CGRectIntersectsRect(planeSprite.boundingBox,bossBulletSprite.boundingBox)){ [planeSprite stopAllActions]; //删除玩家精灵 [batchNode removeChild:planeSprite cleanup:YES]; //爆炸声音 [[SimpleAudioEngine sharedEngine] playEffect:@"b0.mp3"]; //播放爆炸动画 [self bombAnimate:@"blast" :planeSprite.position ]; [self gameOver:@"游戏结束!"]; } } } 修改updateEnemySprite:方法,判断是否更新敌机时增加!isStartBoss进行判断,意味着Boss出动后不再更新敌机。实现代码如下(程序清单同上)。 if (count % 30 == 0 && !isStartBoss) if (count % 200 == 0 && !isStartBoss) 修改update方法,实现代码如下(程序清单同上)。 -(void) update:(ccTime)delta{ count++; [self updateBackground:delta]; [self updateEnemySprite:delta]; [self removeEnemySprite:delta]; [self updateShooting:delta]; [self removeBulletSprite:delta]; self collisionDetection:delta]; [self updateHUD:delta]; [self startBossSprite:delta]; [self moveBossSprite:delta]; [self updateBossShooting:delta]; } 再次编译并运行游戏,当玩家得分达到10000分时,Boss出动。模拟器显示效果如图13.66所示。 当玩家控制飞机攻击大Boss时,Boss的血条会随着生命值的减少而缩短。当Boss生命值为0时,播放爆炸效果,提示游戏胜利,模拟器显示效果如图13.67所示。 到此为止,这个打飞机游戏基本已经开发完成,包括背景滚动、飞机飞行动画、背景音乐、音效、大量敌机攻击、玩家射击、Boss大招、玩家积分统计和游戏设置等功能。记得有位软件大师曾经说过,游戏没有真正意义上的完结,因为开发者总是可以不断地完善它,赋予游戏更多的新元素和新玩法。比如,我们可以让敌机俯冲时发射炮弹、敌机做不规则运动、Boss出动时伴随大量小飞机、玩家飞机增加大炸弹功能、每过一关玩家飞机增加一架等。这个游戏我们暂时就介绍到这里,本节我们的目的是学习使用cocos2d制作一个简单的游戏。游戏虽然简单,但是包括的知识点很多,希望大家好好掌握,将来制作出更加有趣和完美的游戏。 本文转自 fkJava李刚51CTO博客,原文链接:http://blog.51cto.com/javaligang/1402557,如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS开发-View中frame和bounds区别

开发中调整View的时候的经常会遇到frame和bounds,刚开始看的时候不是很清楚,不过看了一下官方文档,frame是确定视图在父视图中的位置,和本身的大小,bounds确定可以确定子视图在当前视图中的位置,还可以改变View的大小,如果bounds确定大小,那么View的视图优先选择的bounds中的宽高。Center的位置是相对于父坐标系中的定位。苹果官方给了一张图片供参考: 如果还不是很清晰,可以参考一下frame和bounds的中代码: 1 2 3 4 5 6 -(CGRect)frame{ return CGRectMake( self .frame.origin.x, self .frame.origin.y, self .frame.size.width, self .frame.size.height); } -(CGRect)bounds{ return CGRectMake(0,0, self .frame.size.width, self .frame.size.height); } 当然为了更好的理解以上的概念,写个小Demo实战了一下,viewDidLoad将图片添加在View中,然后在图片上添加一个View: 1 2 3 4 5 6 7 8 9 UIImageView *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@ "Girl.jpg" ]]; girlImageView.frame=CGRectMake(40, 40, 240, 300); [ self .view addSubview:girlImageView]; //添加到父视图中 NSLog (@ "girlImageView frame:%@------girlImageView bounds:%@" , NSStringFromCGRect (girlImageView.frame), NSStringFromCGRect (girlImageView.bounds)); UIView *childView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; childView.backgroundColor = [UIColor yellowColor]; [girlImageView addSubview:childView]; NSLog (@ "childView frame:%@-------childView bounds:%@" , NSStringFromCGRect (childView.frame), NSStringFromCGRect (childView.bounds)); 具体效果如下: 输出结果: 1 2 2015-04-03 11:50:00.326 MyContraint[1929:98282] girlImageView frame:{{40, 40}, {240, 300}}------girlImageView bounds:{{0, 0}, {240, 300}} 2015-04-03 11:50:00.327 MyContraint[1929:98282] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}} 这个时候如果改变一下UIImageView的bounds,代码如下: 1 2 3 4 5 6 UIImageView *girlImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@ "Girl.jpg" ]]; girlImageView.frame=CGRectMake(40, 40, 240, 300); //改变View中内部原点的位置,同样可以改变frame的宽高 [girlImageView setBounds:CGRectMake(-30, -30, 240, 230)]; [ self .view addSubview:girlImageView]; //添加到父视图中 NSLog (@ "girlImageView frame:%@------girlImageView bounds:%@" , NSStringFromCGRect (girlImageView.frame), NSStringFromCGRect (girlImageView.bounds)); 图片效果: 打印效果如下: 1 2 2015-04-03 11:57:06.738 MyContraint[2019:102665] girlImageView frame:{{40, 75}, {240, 230}}------girlImageView bounds:{{-30, -30}, {240, 230}} 2015-04-03 11:57:06.739 MyContraint[2019:102665] childView frame:{{0, 0}, {100, 100}}-------childView bounds:{{0, 0}, {100, 100}} 通过以上的代码的演示,frame和bounds之间的关系应该很清晰了,如果有疑问,欢迎共同探讨~ 本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4389159.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS 史上最全的图片压缩方法集合

做上传图片功能,特别是类似于微信,QQ里面,公布9张图片, 少不了碰到一个问题,就是图片压缩问题,当然我也遇到了. 我研究了这个问题,发现网上普遍的方法是例如以下 //压缩图片质量 +(UIImage*)reduceImage:(UIImage*)imagepercent:(float)percent { NSData*imageData=UIImageJPEGRepresentation(image,percent); UIImage*newImage=[UIImageimageWithData:imageData]; returnnewImage; } //压缩图片尺寸 +(UIImage*)imageWithImageSimple:(UIImage*)imagescaledToSize:(CGSize)newSize { //Createagraphicsimagecontext UIGraphicsBeginImageContext(newSize); //newsize [imagedrawInRect:CGRectMake(0,0,newSize.width,newSize.height)]; //Getthenewimagefromthecontext UIImage*newImage=UIGraphicsGetImageFromCurrentImageContext(); //Endthecontext UIGraphicsEndImageContext(); //Returnthenewimage. returnnewImage; } 上面的方法比較常见,但是须要载入到内存中来处理图片,当图片数量多了的时候就会收到内存警告,程序崩溃, 我測试过上面方法,上面方法真不好用,真的不推荐大家用.那么我推荐以下这种方法: staticsize_tgetAssetBytesCallback(voidvoid*info,voidvoid*buffer,off_tposition,size_tcount){ ALAssetRepresentation*rep=(__bridgeid)info; NSError*error=nil; size_tcountRead=[repgetBytes:(uint8_t*)bufferfromOffset:positionlength:counterror:&error]; if(countRead==0&&error){ //Wehavenowayofpassingthisinfobacktothecaller,sowelogit,atleast. NDDebug(@"thumbnailForAsset:maxPixelSize:gotanerrorreadinganasset:%@",error); } returncountRead; } staticvoidreleaseAssetCallback(voidvoid*info){ //TheinfohereisanALAssetRepresentationwhichweCFRetaininthumbnailForAsset:maxPixelSize:. //Thisreleasebalancesthatretain. CFRelease(info); } //ReturnsaUIImageforthegivenasset,withsizelengthatmostthepassedsize. //TheresultingUIImagewillbealreadyrotatedtoUIImageOrientationUp,soitsCGImageRef //canbeuseddirectlywithoutadditionalrotationhandling. //Thisisdonesynchronously,soyoushouldcallthismethodonabackgroundqueue/thread. -(UIImage*)thumbnailForAsset:(ALAsset*)assetmaxPixelSize:(NSUInteger)size{ NSParameterAssert(asset!=nil); NSParameterAssert(size>0); ALAssetRepresentation*rep=[assetdefaultRepresentation]; CGDataProviderDirectCallbackscallbacks={ .version=0, .getBytePointer=NULL, .releaseBytePointer=NULL, .getBytesAtPosition=getAssetBytesCallback, .releaseInfo=releaseAssetCallback, }; CGDataProviderRefprovider=CGDataProviderCreateDirect((voidvoid*)CFBridgingRetain(rep),[repsize],&callbacks); CGImageSourceRefsource=CGImageSourceCreateWithDataProvider(provider,NULL); CGImageRefimageRef=CGImageSourceCreateThumbnailAtIndex(source,0,(__bridgeCFDictionaryRef)@{ (NSString*)kCGImageSourceCreateThumbnailFromImageAlways:@YES, (NSString*)kCGImageSourceThumbnailMaxPixelSize:[NSNumbernumberWithInt:size], (NSString*)kCGImageSourceCreateThumbnailWithTransform:@YES, }); CFRelease(source); CFRelease(provider); if(!imageRef){ returnnil; } UIImage*toReturn=[UIImageimageWithCGImage:imageRef]; CFRelease(imageRef); returntoReturn; } 採用上面的方法之后内存占用率非常低。 上面这么长的东西,大家一定看的非常费劲,那么我直接上我源代码,给大家看看,照着我的源代码,写就好了. staticsize_tgetAssetBytesCallback(void*info,void*buffer,off_tposition,size_tcount) { ALAssetRepresentation*rep = (__bridgeid)info; NSError*error =nil; size_tcountRead = [repgetBytes:(uint8_t*)bufferfromOffset:positionlength:counterror:&error]; if(countRead ==0&& error) { // We have no way of passing this info back to the caller, so we log it, at least. NSLog(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error); } returncountRead; } staticvoidreleaseAssetCallback(void*info) { // The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:. // This release balances that retain. CFRelease(info); } //压缩图片 - (UIImage*)thumbnailForAsset:(ALAsset*)asset maxPixelSize:(NSUInteger)size { NSParameterAssert(asset !=nil); NSParameterAssert(size >0); ALAssetRepresentation*rep = [assetdefaultRepresentation]; CGDataProviderDirectCallbackscallbacks = { .version=0, .getBytePointer=NULL, .releaseBytePointer=NULL, .getBytesAtPosition=getAssetBytesCallback, .releaseInfo=releaseAssetCallback, }; CGDataProviderRefprovider =CGDataProviderCreateDirect((void*)CFBridgingRetain(rep), [repsize], &callbacks); CGImageSourceRefsource =CGImageSourceCreateWithDataProvider(provider,NULL); CGImageRefimageRef =CGImageSourceCreateThumbnailAtIndex(source,0, (__bridgeCFDictionaryRef) @{ (NSString*)kCGImageSourceCreateThumbnailFromImageAlways:@YES, (NSString*)kCGImageSourceThumbnailMaxPixelSize: [NSNumbernumberWithInt:size], (NSString*)kCGImageSourceCreateThumbnailWithTransform:@YES, }); CFRelease(source); CFRelease(provider); if(!imageRef) { returnnil; } UIImage*toReturn = [UIImageimageWithCGImage:imageRef]; CFRelease(imageRef); returntoReturn; } 把上面的代码拷贝到project里面,然后调用这种方法就好了,例如以下图: 好了,有问题,欢迎评论给我..... 本文部分内容參考自http://www.lyitnews.com/portal.php?mod=view&aid=1206,感谢他的分享.... 本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5114382.html,如需转载请自行联系原作者

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

用户登录
用户注册
修改密码
忘记密码