issue #398, xcode4 template for box2d & chipmunk

This commit is contained in:
Walzer 2011-06-13 20:35:39 +08:00
parent ac9c735cb5
commit 362ab18c97
19 changed files with 1073 additions and 1 deletions

View File

@ -1,6 +1,8 @@
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
using namespace cocos2d;
using namespace CocosDenshion;
CCScene* HelloWorld::scene()
{

View File

@ -0,0 +1,110 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppDelegate.cpp
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#include "AppDelegate.h"
#include "cocos2d.h"
#include "HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::initInstance()
{
bool bRet = false;
do
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
// Initialize OpenGLView instance, that release by CCDirector when application terminate.
// The HelloWorld is designed as HVGA.
CCEGLView * pMainWnd = new CCEGLView();
CC_BREAK_IF(! pMainWnd
|| ! pMainWnd->Create(TEXT("cocos2d: Hello World"), 320, 480));
#endif // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
// OpenGLView initialized in testsAppDelegate.mm on ios platform, nothing need to do here.
#endif // CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// android does not do anything
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
// Initialize OpenGLView instance, that release by CCDirector when application terminate.
// The HelloWorld is designed as HVGA.
CCEGLView* pMainWnd = new CCEGLView(this);
CC_BREAK_IF(! pMainWnd || ! pMainWnd->Create(320,480));
#ifndef _TRANZDA_VM_
// on wophone emulator, we copy resources files to Work7/TG3/APP/ folder instead of zip file
cocos2d::CCFileUtils::setResource("HelloWorld.zip");
#endif
#endif // CC_PLATFORM_WOPHONE
bRet = true;
} while (0);
return bRet;
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(&CCEGLView::sharedOpenGLView());
// enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
// pDirector->enableRetinaDisplay(true);
// sets landscape mode
pDirector->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);
// turn on display FPS
pDirector->setDisplayFPS(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
CCScene *pScene = HelloWorld::scene();
// run
pDirector->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->pause();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->resume();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}

View File

@ -0,0 +1,51 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppDelegate.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "CCApplication.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by CCDirector.
*/
class AppDelegate : private cocos2d::CCApplication
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief Implement for initialize OpenGL instance, set source path, etc...
*/
virtual bool initInstance();
/**
@brief Implement CCDirector and CCScene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_

View File

@ -0,0 +1,217 @@
//
// HelloWorldScene.cpp
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;
#define PTM_RATIO 32
enum
{
kTagTileMap = 1,
kTagSpriteManager = 1,
kTagAnimation1 = 1,
};
HelloWorld::HelloWorld()
{
setIsTouchEnabled( true );
setIsAccelerometerEnabled( true );
CCSize screenSize = CCDirector::sharedDirector()->getWinSize();
//UXLOG(L"Screen width %0.2f screen height %0.2f",screenSize.width,screenSize.height);
// Define the gravity vector.
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
// Do we want to let bodies sleep?
bool doSleep = true;
// Construct a world object, which will hold and simulate the rigid bodies.
world = new b2World(gravity, doSleep);
world->SetContinuousPhysics(true);
/*
m_debugDraw = new GLESDebugDraw( PTM_RATIO );
world->SetDebugDraw(m_debugDraw);
uint flags = 0;
flags += b2DebugDraw::e_shapeBit;
flags += b2DebugDraw::e_jointBit;
flags += b2DebugDraw::e_aabbBit;
flags += b2DebugDraw::e_pairBit;
flags += b2DebugDraw::e_centerOfMassBit;
m_debugDraw->SetFlags(flags);
*/
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef);
// Define the ground box shape.
b2PolygonShape groundBox;
// bottom
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox, 0);
// top
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox, 0);
// left
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox, 0);
// right
groundBox.SetAsEdge(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox, 0);
//Set up sprite
CCSpriteBatchNode *mgr = CCSpriteBatchNode::spriteSheetWithFile("blocks.png", 150);
addChild(mgr, 0, kTagSpriteManager);
addNewSpriteWithCoords( CCPointMake(screenSize.width/2, screenSize.height/2) );
CCLabelTTF *label = CCLabelTTF::labelWithString("Tap screen", "Marker Felt", 32);
addChild(label, 0);
label->setColor( ccc3(0,0,255) );
label->setPosition( CCPointMake( screenSize.width/2, screenSize.height-50) );
schedule( schedule_selector(HelloWorld::tick) );
}
HelloWorld::~HelloWorld()
{
delete world;
world = NULL;
//delete m_debugDraw;
}
void HelloWorld::draw()
{
// Default GL states: GL_TEXTURE_2D, GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
// Needed states: GL_VERTEX_ARRAY,
// Unneeded states: GL_TEXTURE_2D, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY
glDisable(GL_TEXTURE_2D);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
//world->DrawDebugData();
// restore default GL states
glEnable(GL_TEXTURE_2D);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
}
void HelloWorld::addNewSpriteWithCoords(CCPoint p)
{
//UXLOG(L"Add sprite %0.2f x %02.f",p.x,p.y);
CCSpriteBatchNode* sheet = (CCSpriteBatchNode*)getChildByTag(kTagSpriteManager);
//We have a 64x64 sprite sheet with 4 different 32x32 images. The following code is
//just randomly picking one of the images
int idx = (CCRANDOM_0_1() > .5 ? 0:1);
int idy = (CCRANDOM_0_1() > .5 ? 0:1);
CCSprite *sprite = sheet->createSpriteWithRect( CCRectMake(32 * idx,32 * idy,32,32));
sheet->addChild(sprite);
sprite->setPosition( CCPointMake( p.x, p.y) );
// Define the dynamic body.
//Set up a 1m squared box in the physics world
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
// Define another box shape for our dynamic body.
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
}
void HelloWorld::tick(ccTime dt)
{
//It is recommended that a fixed time step is used with Box2D for stability
//of the simulation, however, we are using a variable time step here.
//You need to make an informed choice, the following URL is useful
//http://gafferongames.com/game-physics/fix-your-timestep/
int velocityIterations = 8;
int positionIterations = 1;
// Instruct the world to perform a single step of simulation. It is
// generally best to keep the time step and iterations fixed.
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the AtlasSprites position and rotation with the corresponding body
CCSprite* myActor = (CCSprite*)b->GetUserData();
myActor->setPosition( CCPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO) );
myActor->setRotation( -1 * CC_RADIANS_TO_DEGREES(b->GetAngle()) );
}
}
}
void HelloWorld::ccTouchesEnded(CCSet* touches, CCEvent* event)
{
//Add a new body/atlas sprite at the touched location
CCSetIterator it;
CCTouch* touch;
for( it = touches->begin(); it != touches->end(); it++)
{
touch = (CCTouch*)(*it);
if(!touch)
break;
CCPoint location = touch->locationInView(touch->view());
location = CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteWithCoords( location );
}
}
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object
CCScene *scene = CCScene::node();
// add layer as a child to scene
CCLayer* layer = new HelloWorld();
scene->addChild(layer);
layer->release();
return scene;
}

View File

@ -0,0 +1,33 @@
//
// HelloWorldScene.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#ifndef __HELLO_WORLD_H__
#define __HELLO_WORLD_H__
// When you import this file, you import all the cocos2d classes
#include "cocos2d.h"
#include "Box2D.h"
class HelloWorld : public cocos2d::CCLayer {
public:
~HelloWorld();
HelloWorld();
// returns a Scene that contains the HelloWorld as the only child
static cocos2d::CCScene* scene();
// adds a new sprite at a given coordinate
void addNewSpriteWithCoords(cocos2d::CCPoint p);
virtual void draw();
virtual void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
void tick(cocos2d::ccTime dt);
private:
b2World* world;
};
#endif // __HELLO_WORLD_H__

View File

@ -0,0 +1,8 @@
//
// Prefix header for all source files of the '___PROJECTNAME___' target in the '___PROJECTNAME___' project
//
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif

Binary file not shown.

View File

@ -0,0 +1,14 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppController.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
@interface ___PROJECTNAMEASIDENTIFIER___AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate> {
UIWindow *window;
}
@end

View File

@ -0,0 +1,98 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppController.mm
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppController.h"
#import "cocos2d.h"
#import "EAGLView.h"
#import "AppDelegate.h"
@implementation ___PROJECTNAMEASIDENTIFIER___AppController
#pragma mark -
#pragma mark Application lifecycle
// cocos2d application instance
static AppDelegate s_sharedApplication;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
EAGLView *__glView = [EAGLView viewWithFrame: [window bounds]
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH_COMPONENT16_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples:0 ];
[window addSubview: __glView];
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
cocos2d::CCApplication::sharedApplication().run();
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
cocos2d::CCDirector::sharedDirector()->pause();
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
cocos2d::CCDirector::sharedDirector()->resume();
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
cocos2d::CCDirector::sharedDirector()->stopAnimation();
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
cocos2d::CCDirector::sharedDirector()->startAnimation();
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[super dealloc];
}
@end

View File

@ -0,0 +1,16 @@
//
// main.m
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
int retVal = UIApplicationMain(argc, argv, nil, @"___PROJECTNAMEASIDENTIFIER___AppController");
[pool release];
return retVal;
}

View File

@ -0,0 +1,110 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppDelegate.cpp
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#include "AppDelegate.h"
#include "cocos2d.h"
#include "HelloWorldScene.h"
USING_NS_CC;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
}
bool AppDelegate::initInstance()
{
bool bRet = false;
do
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
// Initialize OpenGLView instance, that release by CCDirector when application terminate.
// The HelloWorld is designed as HVGA.
CCEGLView * pMainWnd = new CCEGLView();
CC_BREAK_IF(! pMainWnd
|| ! pMainWnd->Create(TEXT("cocos2d: Hello World"), 320, 480));
#endif // CC_PLATFORM_WIN32
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
// OpenGLView initialized in testsAppDelegate.mm on ios platform, nothing need to do here.
#endif // CC_PLATFORM_IOS
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
// android does not do anything
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
// Initialize OpenGLView instance, that release by CCDirector when application terminate.
// The HelloWorld is designed as HVGA.
CCEGLView* pMainWnd = new CCEGLView(this);
CC_BREAK_IF(! pMainWnd || ! pMainWnd->Create(320,480));
#ifndef _TRANZDA_VM_
// on wophone emulator, we copy resources files to Work7/TG3/APP/ folder instead of zip file
cocos2d::CCFileUtils::setResource("HelloWorld.zip");
#endif
#endif // CC_PLATFORM_WOPHONE
bRet = true;
} while (0);
return bRet;
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(&CCEGLView::sharedOpenGLView());
// enable High Resource Mode(2x, such as iphone4) and maintains low resource on other devices.
// pDirector->enableRetinaDisplay(true);
// sets landscape mode
pDirector->setDeviceOrientation(kCCDeviceOrientationLandscapeLeft);
// turn on display FPS
pDirector->setDisplayFPS(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// create a scene. it's an autorelease object
CCScene *pScene = HelloWorld::scene();
// run
pDirector->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->pause();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->resume();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}

View File

@ -0,0 +1,51 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppDelegate.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#ifndef _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "CCApplication.h"
/**
@brief The cocos2d Application.
The reason for implement as private inheritance is to hide some interface call by CCDirector.
*/
class AppDelegate : private cocos2d::CCApplication
{
public:
AppDelegate();
virtual ~AppDelegate();
/**
@brief Implement for initialize OpenGL instance, set source path, etc...
*/
virtual bool initInstance();
/**
@brief Implement CCDirector and CCScene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief The function be called when the application enter background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief The function be called when the application enter foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_

View File

@ -0,0 +1,189 @@
//
// HelloWorldScene.cpp
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;
enum {
kTagBatchNode = 1,
};
static void
eachShape(void *ptr, void* unused)
{
cpShape *shape = (cpShape*) ptr;
CCSprite *sprite = (CCSprite*)shape->data;
if( sprite )
{
cpBody *body = shape->body;
// TIP: cocos2d and chipmunk uses the same struct to store it's position
// chipmunk uses: cpVect, and cocos2d uses CGPoint but in reality the are the same
// since v0.7.1 you can mix them if you want.
sprite->setPosition(CCPointMake(body->p.x, body->p.y));
sprite->setRotation((float) CC_RADIANS_TO_DEGREES( -body->a ));
}
}
HelloWorld::HelloWorld()
{
}
HelloWorld::~HelloWorld()
{
}
CCScene* HelloWorld::scene()
{
// 'scene' is an autorelease object.
CCScene *scene = CCScene::node();
// 'layer' is an autorelease object.
HelloWorld *layer = HelloWorld::node();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
void HelloWorld::addNewSpriteX(float x, float y)
{
int posx, posy;
CCSpriteBatchNode *batch = (CCSpriteBatchNode*) getChildByTag(kTagBatchNode);
posx = (CCRANDOM_0_1() * 200);
posy = (CCRANDOM_0_1() * 200);
posx = (posx % 4) * 85;
posy = (posy % 3) * 121;
CCSprite *sprite = CCSprite::spriteWithBatchNode(batch, CCRectMake(posx, posy, 85, 121));
batch->addChild(sprite);
sprite->setPosition(ccp(x, y));
int num = 4;
cpVect verts[] = {
cpv(-24,-54),
cpv(-24, 54),
cpv( 24, 54),
cpv( 24,-54),
};
cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, cpv(0, 0)));
// TIP:
// since v0.7.1 you can assign CGPoint to chipmunk instead of cpVect.
// cpVect == CGPoint
body->p = cpv(x, y);
cpSpaceAddBody(space, body);
cpShape* shape = cpPolyShapeNew(body, num, verts, cpv(0, 0));
shape->e = 0.5f; shape->u = 0.5f;
shape->data = sprite;
cpSpaceAddShape(space, shape);
}
bool HelloWorld::init()
{
bool ret = false;
if (ret = CCLayer::init())
{
setIsTouchEnabled(true);
CCSize wins = CCDirector::sharedDirector()->getWinSize();
cpInitChipmunk();
cpBody *staticBody = cpBodyNew(INFINITY, INFINITY);
space = cpSpaceNew();
cpSpaceResizeStaticHash(space, 400.0f, 40);
cpSpaceResizeActiveHash(space, 100, 600);
space->gravity = cpv(0, 0);
space->elasticIterations = space->iterations;
cpShape *shape;
// bottom
shape = cpSegmentShapeNew(staticBody, cpv(0,0), cpv(wins.width,0), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
cpSpaceAddStaticShape(space, shape);
// top
shape = cpSegmentShapeNew(staticBody, cpv(0,wins.height), cpv(wins.width,wins.height), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
cpSpaceAddStaticShape(space, shape);
// left
shape = cpSegmentShapeNew(staticBody, cpv(0,0), cpv(0,wins.height), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
cpSpaceAddStaticShape(space, shape);
// right
shape = cpSegmentShapeNew(staticBody, cpv(wins.width,0), cpv(wins.width,wins.height), 0.0f);
shape->e = 1.0f; shape->u = 1.0f;
cpSpaceAddStaticShape(space, shape);
CCSpriteBatchNode *batch = CCSpriteBatchNode::batchNodeWithFile("grossini_dance_atlas.png", 100);
addChild(batch, 0, kTagBatchNode);
addNewSpriteX(200, 200);
schedule(schedule_selector(HelloWorld::step));
}
return ret;
}
void HelloWorld::onEnter()
{
CCLayer::onEnter();
}
void HelloWorld::step(ccTime delta)
{
int steps = 2;
CGFloat dt = delta/(CGFloat)steps;
for(int i=0; i<steps; i++)
{
cpSpaceStep(space, dt);
}
cpSpaceHashEach(space->activeShapes, &eachShape, NULL);
cpSpaceHashEach(space->staticShapes, &eachShape, NULL);
}
void HelloWorld::ccTouchesEnded(CCSet *touches, CCEvent *event)
{
CCSetIterator it;
CCTouch *touch;
for (it = touches->begin(); it != touches->end(); it++) {
touch = (CCTouch*)(*it);
if (! touch) {
break;
}
CCPoint location = touch->locationInView(touch->view());
location = CCDirector::sharedDirector()->convertToGL(location);
addNewSpriteX(location.x, location.y);
}
}

View File

@ -0,0 +1,36 @@
//
// HelloWorldScene.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#ifndef __HELLOW_WORLD_H__
#define __HELLOW_WORLD_H__
#include "cocos2d.h"
// include Chipmunk headers
#include "chipmunk.h"
// HelloWorld Layer
class HelloWorld : public cocos2d::CCLayer {
public:
HelloWorld();
~HelloWorld();
static cocos2d::CCScene* scene();
void step(cocos2d::ccTime dt);
void addNewSpriteX(float x, float y);
virtual void onEnter();
virtual void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent *event);
LAYER_NODE_FUNC(HelloWorld);
private:
bool init();
cpSpace *space;
};
#endif // __HELLOW_WORLD_H__

View File

@ -0,0 +1,8 @@
//
// Prefix header for all source files of the '___PROJECTNAME___' target in the '___PROJECTNAME___' project
//
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif

Binary file not shown.

View File

@ -0,0 +1,14 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppController.h
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
@interface ___PROJECTNAMEASIDENTIFIER___AppController : NSObject <UIAccelerometerDelegate, UIAlertViewDelegate, UITextFieldDelegate,UIApplicationDelegate> {
UIWindow *window;
}
@end

View File

@ -0,0 +1,99 @@
//
// ___PROJECTNAMEASIDENTIFIER___AppController.mm
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppController.h"
#import "cocos2d.h"
#import "EAGLView.h"
#import "AppDelegate.h"
@implementation ___PROJECTNAMEASIDENTIFIER___AppController
#pragma mark -
#pragma mark Application lifecycle
// cocos2d application instance
static AppDelegate s_sharedApplication;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
EAGLView *__glView = [EAGLView viewWithFrame: [window bounds]
pixelFormat: kEAGLColorFormatRGBA8
depthFormat: GL_DEPTH_COMPONENT16_OES
preserveBackbuffer: NO
sharegroup: nil
multiSampling: NO
numberOfSamples: 0 ];
[window addSubview: __glView];
[window makeKeyAndVisible];
[[UIApplication sharedApplication] setStatusBarHidden: YES];
cocos2d::CCApplication::sharedApplication().run();
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
cocos2d::CCDirector::sharedDirector()->pause();
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
cocos2d::CCDirector::sharedDirector()->resume();
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
cocos2d::CCDirector::sharedDirector()->stopAnimation();
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
cocos2d::CCDirector::sharedDirector()->startAnimation();
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[super dealloc];
}
@end

View File

@ -0,0 +1,16 @@
//
// main.m
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//
#import <UIKit/UIKit.h>
int main(int argc, char *argv[]) {
NSAutoreleasePool *pool = [NSAutoreleasePool new];
int retVal = UIApplicationMain(argc, argv, nil, @"___PROJECTNAMEASIDENTIFIER___AppController");
[pool release];
return retVal;
}