SimpleObjectiveChipmunk Example with UIImageView

Official forum for the Chipmunk2D Physics Library.
Post Reply
affect
Posts: 3
Joined: Wed Aug 25, 2010 3:08 am
Contact:

SimpleObjectiveChipmunk Example with UIImageView

Post by affect »

Hello.

We want to use ObjectiveChipmunk for our iPhone Games but i have problems to got it to work.

I have played with the SimpleObjectiveChipmunk Example and replaced the custom button with an UIImageView. Since 2 days i am trying to use the touches events(with pivot joint) to move the UIImageView and then let it fall down again.

Two Problems
1.
When i change the position of the UIImageView's body to"body.pos = cpv(0.0f, 0.0f);" in FallingButton.h then the view is not falling to the lower left corner at start, it falls ~50 pixel to the right. The Button does.

2.
The big Problem, i can not get it to work that i move the UIImageView with the touches events and let it fall down again.
There are weired jumps of the view, there seems to be a problem with the coordinates which i cant figure out.

Thank you for you help

I made minor changes(in red):
FallingButton.h

Code: Select all

#import <Foundation/Foundation.h>

#import "ObjectiveChipmunk.h"

@interface FallingButton : NSObject <ChipmunkObject> {
	//UIButton *button;
	UIImageView *button;
	ChipmunkBody *body;
	NSSet *chipmunkObjects;
	
	int touchShapes;
}

//@property (readonly) UIButton *button;
@property (readonly) UIImageView *button;
@property (readonly) NSSet *chipmunkObjects;
@property int touchedShapes;

- (void)updatePosition;

@end
FallingButton.m

Code: Select all

	/*
		// Set up the UIButton.
		button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setTitle:@"Click Me!" forState:UIControlStateNormal];
		[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
		[button setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
		button.bounds = CGRectMake(0, 0, SIZE, SIZE);
		 */
		
		UIImage *image = [[UIImage alloc] init];
		UIImageView *imageView = [[UIImageView alloc] init];
		image = [UIImage imageNamed:@"logo.png"];
		imageView = [[UIImageView alloc] initWithImage: image];
		imageView.userInteractionEnabled = YES;
		imageView.bounds = CGRectMake(0, 0, SIZE, SIZE);
		button = imageView;
ViewController.h

Code: Select all

@interface ViewController : UIViewController <UIAccelerometerDelegate> {
	CADisplayLink *displayLink;
	ChipmunkSpace *space;
	FallingButton *fallingButton;
	cpVect mousePoint;
	cpVect mousePoint_last;
	ChipmunkBody *mouseBody;
	ChipmunkConstraint *mouseJoint;
}

@end
In ViewController.m i added gravity and touchesBegan/touchesMoved/touchesEnded:

Code: Select all

 
	// Create and initialize the Chipmunk space.
	// Chipmunk spaces are containers for simulating physics.
	// You add a bunch of objects and joints to the space and the space runs the physics simulation on them all together.
	space = [[ChipmunkSpace alloc] init];
	
	[space setGravity:cpv(0, 982)];
	[space setElasticIterations:10];
	
	// This method adds four static line segment shapes to the space.
	// Most 2D physics games end up putting all the gameplay in a box. This method just makes that easy.
	// We'll tag these segment shapes with the borderType object. You'll see what this is for next.
	[space addBounds:self.view.bounds thickness:10.0f elasticity:1.0f friction:1.0f layers:CP_ALL_LAYERS group:CP_NO_GROUP collisionType:borderType];
.
.
.
mouseBody = [[ChipmunkBody alloc] initStaticBody];

Code: Select all

// This method is called each frame to update the scene.
// It is called from the display link every time the screen wants to redraw itself.
- (void)update {
	// Step (simulate) the space based on the time since the last update.
	cpFloat dt = displayLink.duration*displayLink.frameInterval;
	cpVect newPoint = cpvlerp(mousePoint_last, mousePoint, 0.25f);
	mouseBody.pos = newPoint;
	mouseBody.vel = cpvmult(cpvsub(newPoint, mousePoint_last), 1.0f/dt);
	mousePoint_last = newPoint;
	[space step:dt];
	
	// Update the button.
	// This sets the position and rotation of the button to match the rigid body.
	[fallingButton updatePosition];
}

Code: Select all


static float hh = 639.0/2.0, hw = 479.0/2.0;
static cpVect
mouseToSpace(cpVect pos, CGSize size)
{
	cpVect v = cpvsub(cpvmult(cpv(pos.y/size.height, pos.x/size.width), 2.0f), cpv(1.0f, 1.0f));
	v = cpv(v.x*hw, v.y*hh);
	//	printf("%s\n", cpvstr(v));
	return v;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	
	// We only support single touches, so anyObject retrieves just that touch from touches
	UITouch *touch = [[event touchesForView:[self view]] anyObject];
	
	
	cpVect point = mouseToSpace([touch locationInView:[self view]], [[touch view] bounds].size);
	//	NSLog(@"down %s", cpvstr(point));
	
	mousePoint = point;
	NSLog(@"%s\n", cpvstr(point));
	
	ChipmunkShape *shape = [space pointQueryFirst:point layers:GRABABLE_MASK_BIT group:nil];
	if(shape){
		ChipmunkBody *body = shape.body;
		
		mousePoint_last = mousePoint;
		mouseBody.pos = mousePoint;
		
		mouseJoint = [space add: [ChipmunkPivotJoint pivotJointWithBodyA:mouseBody bodyB:body anchr1:cpvzero anchr2:[body world2local:point]]];
		mouseJoint.maxForce = 50000.0f;
		mouseJoint.biasCoef = 0.15f;
	}
	
	
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	
	UITouch *touch = [[event touchesForView:[self view]] anyObject];
	mousePoint = mouseToSpace([touch locationInView:[self view]], [[touch view] bounds].size);
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	[space remove:mouseJoint];
	mouseJoint = nil;
}
Paul10
Posts: 17
Joined: Sat Jul 31, 2010 8:27 am
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by Paul10 »

Chipmunk uses different Y coordinates than the iphone - Y (0,0) starts at the lower left...vs iphone uikit of top left.

In my touchesBegin code, I do something like:

Code: Select all

UITouch *touch = [[event allTouches] anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
cpVect point = cpv(touchLocation.x, 480 - touchLocation.y);
I'm using C chipmunk, not objective-c but you get the idea. So, when you click the iphone screen, the y coords have to be converted before you send them to chipmunk.

At least that's what I'm doing in my code.
User avatar
slembcke
Site Admin
Posts: 4166
Joined: Tue Aug 14, 2007 7:13 pm
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by slembcke »

I think that you should be able to just use [touch locationInView:[self view]] without having to convert it at all. The coordinate system used is simply the local coordinates of the parent view.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
Paul10
Posts: 17
Joined: Sat Jul 31, 2010 8:27 am
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by Paul10 »

Is that an advantage of using the objective-c chipmunk....no need to convert coordinates?
User avatar
slembcke
Site Admin
Posts: 4166
Joined: Tue Aug 14, 2007 7:13 pm
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by slembcke »

No, Chipmunk doesn't assume any sort of coordinate system. In this case the view's coordinates are the Chipmunk coordinates. OpenGL lets you set up your coordinate system however you want, which is why you must convert the coordinates.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
affect
Posts: 3
Joined: Wed Aug 25, 2010 3:08 am
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by affect »

@slembcke
"[touch locationInView:[self view]]" does not work with UIButton but "almost" with UIImageView.

@Paul10
Your solution works for the UIButton but i have to click on the opposide of the screen. Button is bottom, i have to click on top. I have to move down the mouse and the button goes up Lef/right is ok.

With an UIImageView both solutions work, but the screen seems to be 50 pixel to the right and to the bottom.
Here are the Screenshots:
1. UIButton lower left corner
2. UIImageView lower left corner
3. UIImageview lower right corner
Image Image Image

thank you for your help!
Paul10
Posts: 17
Joined: Sat Jul 31, 2010 8:27 am
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by Paul10 »

slembcke wrote:No, Chipmunk doesn't assume any sort of coordinate system.
Hmm. If this is true, then what I've attempted to code on my own must be incorrect. Anytime I pass a Y coord to chipmunk, I need to do a 480 - y on it. I'm not running in OpenGL or cocos2d. I'm running in a regular windows based iphone app (portrait mode). I'm using the interface builder with my images and using them within the chipmunk space. Seems to work all ok, except I have to pass the 480 stuff.

If chipmunk doesnt care about the x,y coords of shape/body placements, I must be doing something wrong.

Hmm, maybe I should start another thread on this? I definitely don't want to keep going with my app if I'm not using the framework correctly :(

-Paul
User avatar
slembcke
Site Admin
Posts: 4166
Joined: Tue Aug 14, 2007 7:13 pm
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by slembcke »

It sounds like you treating your Chipmunk space where the positive y axis is up. I consider this "normal" as I find it easier to reason with. Cocoa views treat the positive y axis as going down the screen.

If you simply create your world assuming that the positive y axis is down, then your coordinates match up with Cocoa's.
Can't sleep... Chipmunks will eat me...
Check out our latest projects! -> http://howlingmoonsoftware.com/wordpress/
affect
Posts: 3
Joined: Wed Aug 25, 2010 3:08 am
Contact:

Re: SimpleObjectiveChipmunk Example with UIImageView

Post by affect »

Solution found.

1.
UIButton has its center at (0,0), UIImageView at (width/2, height/2). Setting the center of image view to (0,0) show this view correctly at screen like the button.

2.
"[touch locationInView:[self view]]" with button does not work because UIButton do not respond to touches events in ViewController.

Solution:
Using UIImageView with center (0, 0) and using "cpVect point = [touch locationInView:[self view]]" does work as expected on iPhone and iPad.


@Paul10
I dont use OpenGL/cocos2d too, no need to use "480-...".

Thanks.
Post Reply

Who is online

Users browsing this forum: No registered users and 15 guests