Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting gravity to newly created entity #2

Open
tomhallam opened this issue Sep 28, 2013 · 1 comment
Open

Setting gravity to newly created entity #2

tomhallam opened this issue Sep 28, 2013 · 1 comment

Comments

@tomhallam
Copy link

Hi there,

I hope this isn't a bad question, but I couldn't really understand your application of forces in the gravity tutorial.

With the following code:

                    var obj = _this.world.addEntity({
                        imgSrc: 'enemy.png',
                        radiusPixels: 20,
                        xPixels: Math.floor(Math.random() * canvas.width),
                        yPixels: 0,
                        //angleRadians: 45,
                        angularVelRadians: 10
                    });

How can I set the gravity of the newly created object to something like 0.5?
obj.body.ApplyForce(0,0) // for example, made everything mess up

I don't really understand the concept at the moment, a quick explanation would get me back on track.

Thanks for the great library :)

@jcole
Copy link
Owner

jcole commented Oct 1, 2013

Hi, the gravity is set for the world in general. In the Gravity demo, gravity is set to 0 in both the X and Y-directions.

What makes the objects actually attract each other is calculating the force between them based on the formula:

force = some_constant * mass of object1 * mass of object2 / (distance between them)^2

  # some low-level Box2d action here
  applyGravities = (obj1, obj2) ->
    pos1 = obj1.body.GetWorldCenter()
    pos2 = obj2.body.GetWorldCenter()
    diffVec = pos2.Copy()
    diffVec.Subtract(pos1)
    distSq = diffVec.LengthSquared()
    forceMagnitude = gravitationalConstant * obj1.body.GetMass() * obj2.body.GetMass() / distSq
    diffVec.Normalize()    
    diffVec.Multiply(forceMagnitude)
    obj1.body.ApplyForce(diffVec, pos1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants