Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A (physical) string with a weight in iOS

I'd like to implement a (physical) string with a weight in iOS, that reacts to accelerometer input and colides against the view bounds.

enter image description here

What is the simplest way to do this? I would prefer to avoid using external frameworks like Box2D, unless of course a native solution is too complicated.

like image 718
hpique Avatar asked Dec 27 '22 06:12

hpique


1 Answers

If you need it to accelerate under gravity and bounce realistically when it hits the edge, you'll need to use a physics framework (unless you feel like getting out a physics book and doing the equations yourself) as there's nothing like that built into UIKit.

I'd recommend you try Chipmunk instead of Box2D. I've found it easier to use with Cocoa as it's pure C and not C++. It also has an Objective-C wrapper, but the developer charges for it (the plain C library is free).

Here's a simple iPhone Chipmunk physics example I put together.

It uses the accelerometer and UIKit for drawing - just replace the crates with your own objects. (The accelerometer doesn't work in the simulator, you'll have to try it on a phone).

UPDATE: now you've added the image I realise you mean a bob on a string (I thought you meant a UILabel that falls around the screen, lol!). Here's another example that includes a tether between crates. If you use this plus the Chipmunk docs you should be able to figure out what to do.

You'll need to attach one end of the string to a static object, or one with infinite mass (not included in my example).

If you want a realistic string, you'll need to break it up into several short constraints instead of just one long one, but I suggest you start simple if you've not got much experience with physics libraries.

like image 71
Nick Lockwood Avatar answered Jan 04 '23 22:01

Nick Lockwood