Created
August 7, 2013 20:33
-
-
Save segphault/6178359 to your computer and use it in GitHub Desktop.
Attempting to make a bouncing ball with Cocos2D XNA and Box2D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Cocos2D; | |
using Box2D.Dynamics; | |
using Box2D.Common; | |
using Box2D.Collision.Shapes; | |
using Microsoft.Xna.Framework; | |
namespace Cocos2DGame1 | |
{ | |
public class IntroLayer : CCLayerColor | |
{ | |
float PtmRatio = 32f; | |
b2World World; | |
CCSize WinSize { get { return CCDirector.SharedDirector.WinSize; } } | |
public IntroLayer() | |
{ | |
var ballSprite = new CCSprite ("ball.png", new CCRect (0, 0, 80, 80)); | |
ballSprite.Position = new CCPoint (WinSize.Center.X, WinSize.Height); | |
AddChild (ballSprite); | |
var gravity = new b2Vec2 (0.0f, -9.8f); | |
World = new b2World (gravity); | |
World.SetContinuousPhysics (true); | |
var ballBodyDef = b2BodyDef.Create (); | |
ballBodyDef.userData = ballSprite; | |
ballBodyDef.type = b2BodyType.b2_dynamicBody; | |
ballBodyDef.position.Set (ballSprite.PositionX / PtmRatio, | |
ballSprite.PositionY / PtmRatio); | |
var ballBody = World.CreateBody (ballBodyDef); | |
var circle = new b2CircleShape (); | |
circle.Radius = 80f / PtmRatio; | |
var ballShapeDef = new b2FixtureDef (); | |
ballShapeDef.shape = circle; | |
ballShapeDef.density = 1.0f; | |
ballShapeDef.friction = 0.2f; | |
ballShapeDef.restitution = 0.8f; | |
ballBody.CreateFixture (ballShapeDef); | |
var groundBodyDef = b2BodyDef.Create(); | |
groundBodyDef.position.Set (0, 0); | |
var groundBody = World.CreateBody (groundBodyDef); | |
var groundEdge = new b2EdgeShape (); | |
groundEdge.Set (new b2Vec2 (0, 0), new b2Vec2 (WinSize.Width / PtmRatio, 0)); | |
groundBody.CreateFixture (groundEdge, 0); | |
} | |
void Step(float dt) | |
{ | |
World.Step (dt, 5, 1); | |
for (var body = World.BodyList; body != null; body = body.Next) { | |
if (body.UserData != null) { | |
var ball = body.UserData as CCSprite; | |
ball.PositionX = body.Position.x * PtmRatio; | |
ball.PositionY = body.Position.y * PtmRatio; | |
ball.Rotation = -1 * CCMacros.CCRadiansToDegrees (body.Angle); | |
} | |
} | |
} | |
public override void OnEnter () | |
{ | |
base.OnEnter (); | |
Schedule (Step); | |
} | |
public static CCScene Scene | |
{ | |
get | |
{ | |
var scene = new CCScene(); | |
var layer = new IntroLayer(); | |
scene.AddChild(layer); | |
return scene; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment