⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crashlandingappdelegate.m

📁 在iPhone OS上使用用Objective-C语言开发的Demo程序
💻 M
📖 第 1 页 / 共 2 页
字号:
/*===== IMPORTANT =====This is sample code demonstrating API, technology or techniques in development.Although this sample code has been reviewed for technical accuracy, it is notfinal. Apple is supplying this information to help you plan for the adoption ofthe technologies and programming interfaces described herein. This informationis subject to change, and software implemented based on this sample code shouldbe tested with final operating system software and final documentation. Newerversions of this sample code may be provided with future seeds of the API ortechnology. For information about updates to this and other developerdocumentation, view the New & Updated sidebars in subsequent documentationseeds.=====================File: CrashLandingAppDelegate.mAbstract: The UIApplication delegate class, which is the central controller ofthe application.Version: 1.6Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc.("Apple") in consideration of your agreement to the following terms, and youruse, installation, modification or redistribution of this Apple softwareconstitutes acceptance of these terms.  If you do not agree with these terms,please do not use, install, modify or redistribute this Apple software.In consideration of your agreement to abide by the following terms, and subjectto these terms, Apple grants you a personal, non-exclusive license, underApple's copyrights in this original Apple software (the "Apple Software"), touse, reproduce, modify and redistribute the Apple Software, with or withoutmodifications, in source and/or binary forms; provided that if you redistributethe Apple Software in its entirety and without modifications, you must retainthis notice and the following text and disclaimers in all such redistributionsof the Apple Software.Neither the name, trademarks, service marks or logos of Apple Inc. may be usedto endorse or promote products derived from the Apple Software without specificprior written permission from Apple.  Except as expressly stated in this notice,no other rights or licenses, express or implied, are granted by Apple herein,including but not limited to any patent rights that may be infringed by yourderivative works or by other works in which the Apple Software may beincorporated.The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NOWARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIEDWARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR INCOMBINATION WITH YOUR PRODUCTS.IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTEGOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/ORDISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OFCONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IFAPPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.Copyright (C) 2008 Apple Inc. All Rights Reserved.*/#import <mach/mach_time.h>#import "CrashLandingAppDelegate.h"#import "MyEAGLView.h"#import "SoundEngine.h"// CONSTANTS#define kUserNameDefaultKey			@"userName"   // NSString#define kHighScoresDefaultKey		@"highScores" // NSArray of NSStrings#define kAccelerometerFrequency		100 // Hz#define kFilteringFactor			0.1 // For filtering out gravitational affects#define kRenderingFPS				30.0 // Hz#define kListenerDistance			1.0  // Used for creating a realistic sound field// MACROS// Converts degrees to radians for calculating the orientation of the rocket.#define DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI)// Used to randomize the starting condtions of the game#define RANDOM_SEED() srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF))// Used to randomize the position of the base the rocket must land on.#define RANDOM_FLOAT() ((float)random() / (float)INT32_MAX)// CLASS INTERFACE@interface CrashLandingAppDelegate ()- (void) renderScene;- (void) resetGame;- (void) saveScore;@end// CLASS IMPLEMENTATIONS@implementation CrashLandingAppDelegate+ (void) initialize {	if(self == [CrashLandingAppDelegate class]) {		RANDOM_SEED();		//Make sure we have a default set of high-scores in the preferences		[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObject:[NSArray array] forKey:kHighScoresDefaultKey]];	}}- (void) applicationDidFinishLaunching:(UIApplication*)application {	NSBundle*				bundle = [NSBundle mainBundle];	CGRect					rect = [[UIScreen mainScreen] bounds];			// Set up variable for starting the game	_firstTap = YES;		//Create and editable text field. This is used only when the user successfully lands the rocket.	_textField = [[UITextField alloc] initWithFrame:CGRectMake(60, 214, 200, 30)];	[_textField setDelegate:self];	[_textField setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.5]];	[_textField setTextColor:[UIColor whiteColor]];	[_textField setFont:[UIFont fontWithName:kFontName size:kStatusFontSize]];	[_textField setPlaceholder:@"Tap to edit"];			//Set up OpenGL projection matrix	glMatrixMode(GL_PROJECTION);	glOrthof(0, rect.size.width, 0, rect.size.height, -1, 1);	glMatrixMode(GL_MODELVIEW);		//Initialize OpenGL states	glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);	glEnable(GL_TEXTURE_2D);	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);	glEnableClientState(GL_VERTEX_ARRAY);	glEnableClientState(GL_TEXTURE_COORD_ARRAY);		//Loadthe  background texture and configure it	_textures[kTexture_Title] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"Title.png"]];	glBindTexture(GL_TEXTURE_2D, [_textures[kTexture_Title] name]);	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);		//Load other textures	_textures[kTexture_Lander] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"Ship.png"]];	_textures[kTexture_Base] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"Platform.png"]];	_textures[kTexture_MainThrust] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"ThrustMiddle.png"]];	_textures[kTexture_LeftThrust] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"ThrustLeft.png"]];	_textures[kTexture_RightThrust] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"ThrustRight.png"]];	_textures[kTexture_Explosion] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"Explosion.png"]];	_textures[kTexture_FuelBar] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"EmptyFuelBar.png"]];	_textures[kTexture_FuelLevel] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"FuelBar.png"]];	_textures[kTexture_LightGreen] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"LightGreen.png"]];	_textures[kTexture_LightRed] = [[Texture2D alloc] initWithImage: [UIImage imageNamed:@"LightRed.png"]];	_textures[kTexture_LabelSpeed] = [[Texture2D alloc] initWithString:@"Speed" dimensions:CGSizeMake(64, 32) alignment:UITextAlignmentLeft fontName:kFontName fontSize:kLabelFontSize];	_textures[kTexture_LabelAngle] = [[Texture2D alloc] initWithString:@"Angle" dimensions:CGSizeMake(64, 32) alignment:UITextAlignmentLeft fontName:kFontName fontSize:kLabelFontSize];	_textures[kTexture_LabelPosition] = [[Texture2D alloc] initWithString:@"Position" dimensions:CGSizeMake(64, 32) alignment:UITextAlignmentLeft fontName:kFontName fontSize:kLabelFontSize];		// Note that each of the Sound Engine functions defined in SoundEngine.h return an OSStatus value.	// Although the code in this application does not check for errors, you'll want to add error checking code 	// in your own application, particularly during development.	//Setup sound engine. Run  it at 44Khz to match the sound files	SoundEngine_Initialize(44100);	// Assume the listener is in the center at the start. The sound will pan as the position of the rocket changes.	SoundEngine_SetListenerPosition(0.0, 0.0, kListenerDistance);	// Load each of the four sounds used in the game.	SoundEngine_LoadEffect([[bundle pathForResource:@"Start" ofType:@"caf"] UTF8String], &_sounds[kSound_Start]);	SoundEngine_LoadEffect([[bundle pathForResource:@"Success" ofType:@"caf"] UTF8String], &_sounds[kSound_Success]);	SoundEngine_LoadEffect([[bundle pathForResource:@"Failure" ofType:@"caf"] UTF8String], &_sounds[kSound_Failure]);	SoundEngine_LoadLoopingEffect([[bundle pathForResource:@"Thrust" ofType:@"caf"] UTF8String], NULL, NULL, &_sounds[kSound_Thrust]);		// Compute the land's "bounds"	_landerBounds = CGRectMake(0, 0, 84, 66);	_landerBounds = CGRectOffset(_landerBounds, -_landerBounds.size.width / 2, -_landerBounds.size.height / 2);		//Show window//	[_window makeKeyAndVisible];		//Configure and start accelerometer	[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / kAccelerometerFrequency)];	[[UIAccelerometer sharedAccelerometer] setDelegate:self];		//Render the Title frame 	glDisable(GL_BLEND);	[_textures[kTexture_Title] drawInRect:[glView bounds]];	glEnable(GL_BLEND);		//Swap the framebuffer	[glView swapBuffers];}// Release resources when they are no longer needed- (void) dealloc {	unsigned			i;		[_statusTexture release];		SoundEngine_Teardown();		for(i = 0; i < kNumTextures; ++i)		[_textures[i] release];		[_textField release];	[glView release];	[window release];		[super dealloc];}// Implement this method to get the lastest data from the accelerometer - (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration {	//Use a basic low-pass filter to only keep the gravity in the accelerometer values	_accelerometer[0] = acceleration.x * kFilteringFactor + _accelerometer[0] * (1.0 - kFilteringFactor);	_accelerometer[1] = acceleration.y * kFilteringFactor + _accelerometer[1] * (1.0 - kFilteringFactor);	_accelerometer[2] = acceleration.z * kFilteringFactor + _accelerometer[2] * (1.0 - kFilteringFactor);}// Saves the user name and score after the user enters it in the provied text field. - (void)textFieldDidEndEditing:(UITextField*)textField {	//Save name	[[NSUserDefaults standardUserDefaults] setObject:[textField text] forKey:kUserNameDefaultKey];		//Save the score	[self saveScore];}// Terminates the editing session- (BOOL)textFieldShouldReturn:(UITextField*)textField {	//Terminate editing	[textField resignFirstResponder];		return YES;}// Called by touchesEnded:withEvent: when the user taps the screen- (void)handleTap {		if (_firstTap){ // Replace the title screen with the background		//Load background texture and configure it		_textures[kTexture_Background] = [[Texture2D alloc] initWithImage:[UIImage imageNamed:@"Background.png"]];		glBindTexture(GL_TEXTURE_2D, [_textures[kTexture_Background] name]);		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);		//Reset		[self resetGame];		_firstTap = NO;	} else { // Either the user tapped to start a new game or the user successfully landed the rocket.		//Stop rendering timer		[_timer invalidate];		_timer = nil;				//In the lander was landed successfully, save the current score or start a new game		if(_state == kState_Success)			[self saveScore];

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -