Book Image

Lua Game Development Cookbook

By : Mario Kasuba, Mário Kašuba
Book Image

Lua Game Development Cookbook

By: Mario Kasuba, Mário Kašuba

Overview of this book

Table of Contents (16 chapters)
Lua Game Development Cookbook
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Moving objects


Dynamic objects can be moved primarily by using forces. Moving objects by setting their position manually is not recommended because you can easily miss an object collision this way. However, you can set an object's position at the start of your game to adjust the initial object location.

Getting ready

For this recipe, you'll need a dynamic object with a nonzero mass and density:

local body_def = box2d.BodyDef()
body_def.type = 'dynamic'
body_def.position = Vec(0,0)
body_def.angle = 0

local body = world.createBody(body_def)
local shape = box2d.CircleShape()
shape.radius = 1

local fixture_def = box2d.FixtureDef()
fixture_def.shape = shape
fixture_def.density = 1.5
fixture_def.friction = 0.3
fixture_def.restitution = 0.2

local fixture = body.createFixture(fixture_def)

How to do it…

In the real world, you have to use a force to move objects. There are two ways in which you can apply a force to move objects in Box2D—the continual force and impulses.

The continual force

The continual...