This document discusses Box2D, a 2D physics engine, and how it can be used with libGDX, an open-source game development framework. It provides an overview of Box2D concepts like the world, bodies, fixtures, shapes, and joints. It also discusses how to set up a Box2D world in libGDX, create dynamic and static bodies, add fixtures to bodies, and render physics simulations. The document includes code examples for creating a Box2D world, bodies, and handling the physics step to update simulations over time.
A split screen-viable UI event system - Unite Copenhagen 2019Unity Technologies
Learn about the implementation of a 2-player split-screen user interface (UI) in Battle Planet Judgement Day. In Unity, the Event System allows only one element to be currently selected, which can be a problem when designing split screen UI. In this session, you'll discover how this issue was addressed in Battle Planet Judgement Day, the ups and downs of the implementation, insights on pitfalls to avoid and best practices learned during the time of development. We hope this will help you learn how to implement your own solution.
Speaker: Kevin Hagen - Threaks
Session available here: https://youtu.be/aR5UXatawmE
Cross-scene references: A shock to the system - Unite Copenhagen 2019Unity Technologies
Discover the GUID Based reference workflow, with a focus on Multi-Scene workflows, save game, and how these all came together in System Shock 3. You'll learn about the reason for wanting a stable instance Id, why Unity doesn't have one out of the box, what this implementation does, and how you can use it in your own projects. System Shock 3 is a great example of this tool's power, but demonstrates how it can be tricky too.
Speaker:
William Armstrong - Unity
Take a dive deep into the new prefab features with developers Steen Lund. What's the inside versus outside of a prefab? How does it relate to Prefab mode, overrides, unpacking, and prefab variants? How has the new prefab back-end changed? This session will give you a better understanding of the Prefab system, the pros and cons of various implementation decisions, and some Aha moments working with Prefab nesting.
A split screen-viable UI event system - Unite Copenhagen 2019Unity Technologies
Learn about the implementation of a 2-player split-screen user interface (UI) in Battle Planet Judgement Day. In Unity, the Event System allows only one element to be currently selected, which can be a problem when designing split screen UI. In this session, you'll discover how this issue was addressed in Battle Planet Judgement Day, the ups and downs of the implementation, insights on pitfalls to avoid and best practices learned during the time of development. We hope this will help you learn how to implement your own solution.
Speaker: Kevin Hagen - Threaks
Session available here: https://youtu.be/aR5UXatawmE
Cross-scene references: A shock to the system - Unite Copenhagen 2019Unity Technologies
Discover the GUID Based reference workflow, with a focus on Multi-Scene workflows, save game, and how these all came together in System Shock 3. You'll learn about the reason for wanting a stable instance Id, why Unity doesn't have one out of the box, what this implementation does, and how you can use it in your own projects. System Shock 3 is a great example of this tool's power, but demonstrates how it can be tricky too.
Speaker:
William Armstrong - Unity
Take a dive deep into the new prefab features with developers Steen Lund. What's the inside versus outside of a prefab? How does it relate to Prefab mode, overrides, unpacking, and prefab variants? How has the new prefab back-end changed? This session will give you a better understanding of the Prefab system, the pros and cons of various implementation decisions, and some Aha moments working with Prefab nesting.
At Unite Copenhagen, this talk detailed the process of converting GameObjects to Entities and how this can be extended and customized.
Speakers:
Simon Mogensen – Unity
Fabrice Léte – Unity Technologies
Watch the session on YouTube: https://youtu.be/TdlhTrq1oYk
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Unity Technologies
Get a high-level overview of the Entity Component System (ECS) and turn-based game loops, and see a proof of concept built using ECS. These slides will cover some of the pitfalls and also show concepts of ECS in a slightly exotic context.
Speaker:
Florian Uhde - Three Eyed Games
Watch the session on YouTube: https://youtu.be/mL4qrt-15TE
Custom SRP and graphics workflows - Unite Copenhagen 2019Unity Technologies
Battle Planet - Judgement Day is a unique game in the sense that it's played entirely on a single sphere (the planet). Levels are fully procedural and fully destructible. This structure created a few big challenges in terms of rendering, which were solved by writing a custom Scriptable Render Pipeline for the game. This session provides an overview of the game's rendering features and how they were implemented using SRP. It includes a few examples of how performance issues influenced the design of the pipeline as well as a discussion about shader programming and design patterns.
Speaker:
Henning Steinbock - Threaks
Session available here: https://youtu.be/91zUwJwkXNQ
Test Driven Game Development with Cocos2d.
This is the first part of my 8th Light University talk on how to effectively write unit tests for game development. We're using Cocos2d for the framework, but the principles apply to most game frameworks.
Introduction to Game Programming TutorialRichard Jones
The slides to accompany the Introduction to Game Programming tutorial I ran at LCA 2010. The tutorial ran over 90 minutes with the participants following along.
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019Unity Technologies
The use of Unity in film and animation pipelines is still a growing area, and the best way to get started isn't often clear to new users. We'll cover the necessary methods and steps for getting data from external content sources into and out of Unity, with a focus on industry standard technologies and applications, such as Universal Scene Description (USD) and Alembic.
Speaker:
Chris Redmann - Unity
Watch the session on YouTube: https://youtu.be/BtKMvecBIbc
At Unite Copenhagen, this talk detailed the process of converting GameObjects to Entities and how this can be extended and customized.
Speakers:
Simon Mogensen – Unity
Fabrice Léte – Unity Technologies
Watch the session on YouTube: https://youtu.be/TdlhTrq1oYk
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Unity Technologies
Get a high-level overview of the Entity Component System (ECS) and turn-based game loops, and see a proof of concept built using ECS. These slides will cover some of the pitfalls and also show concepts of ECS in a slightly exotic context.
Speaker:
Florian Uhde - Three Eyed Games
Watch the session on YouTube: https://youtu.be/mL4qrt-15TE
Custom SRP and graphics workflows - Unite Copenhagen 2019Unity Technologies
Battle Planet - Judgement Day is a unique game in the sense that it's played entirely on a single sphere (the planet). Levels are fully procedural and fully destructible. This structure created a few big challenges in terms of rendering, which were solved by writing a custom Scriptable Render Pipeline for the game. This session provides an overview of the game's rendering features and how they were implemented using SRP. It includes a few examples of how performance issues influenced the design of the pipeline as well as a discussion about shader programming and design patterns.
Speaker:
Henning Steinbock - Threaks
Session available here: https://youtu.be/91zUwJwkXNQ
Test Driven Game Development with Cocos2d.
This is the first part of my 8th Light University talk on how to effectively write unit tests for game development. We're using Cocos2d for the framework, but the principles apply to most game frameworks.
Introduction to Game Programming TutorialRichard Jones
The slides to accompany the Introduction to Game Programming tutorial I ran at LCA 2010. The tutorial ran over 90 minutes with the participants following along.
Unity asset workflows for Film and Animation pipelines - Unite Copenhagen 2019Unity Technologies
The use of Unity in film and animation pipelines is still a growing area, and the best way to get started isn't often clear to new users. We'll cover the necessary methods and steps for getting data from external content sources into and out of Unity, with a focus on industry standard technologies and applications, such as Universal Scene Description (USD) and Alembic.
Speaker:
Chris Redmann - Unity
Watch the session on YouTube: https://youtu.be/BtKMvecBIbc
Useful Tools for Making Video Games - Newton (2008)Korhan Bircan
A presentations I gave back in 2008 when I was the teaching assistant for Innovating Game Development course in Brown University.
This is an overview of the popular Newton physics engine. I talk about using materials and callback functions, various types of joints and constraints and give pointers to integrating Newton with Irrlicht and Ogre.
public void turnRight(double degrees) {rotationInDegrees + - = deg.pdfisenbergwarne4100
public void turnRight(double degrees) {
rotationInDegrees + - = degrees;
}
public void turnLeft(double degrees) {
rotationInDegrees - = degrees;
}
Actor
public class Actor {
private EZImage pikachu; // Member variable to store bug picture
private int x, y, startx, starty; // Member variables to store x, y, startx, starty
private int destx, desty; // Member variables to store destination values
private long starttime; // Member variable to store the start time
private long duration; // Member variable to store the duration
private boolean interpolation; // Member variable that is set to true if it is in the
interpolation state
// ********* SCALE
private float currentScale = 1;
private float destScale = 1;
private float startScale = 1;
private boolean interpolationScale;
// Constructor for RCBug takes 3 parameters
public Actor(String filename,int posx, int posy){
// Set the current position of the bug
x=posx;y=posy;
// Create the image of the bug
pikachu = EZ.addImage(filename, posx, posy);
// Move it to the starting position. This is actually redundant.
pikachu.translateTo(x,y);;
// Set interpolation mode to false initially
interpolation = false;
interpolationScale = false;
}
// Set the destination by giving it 3 variables
// Dur means duration and is measured in seconds
//public void setDestination(int posx, int posy, long dur){
public void moveto(int posx, int posy, long dur){
// Set destination position and duration
// Convert seconds to miliseconds
destx = posx; desty = posy; duration = dur*1000;
// Get the startting time (i.e. time according to your computer)
starttime = System.currentTimeMillis();
// Set the starting position of your bug
startx=x; starty=y;
// Set interolation mode to true
interpolation = true;
interpolationScale = false;
}
// ********* SCALE
public void setScale(float s, float dur){
destScale = s;
starttime = System.currentTimeMillis();
startScale = currentScale;
interpolationScale = true;
}
// If you?re in interpolation state then return true, else false.
public boolean moving() {
return interpolation;
}
// ********* SCALE
public boolean scaling() {
return interpolationScale;
}
// This moves the bug based on the current time and elapsed time according to the interpolation
equation
public void go(){
// If interpolation mode is true then do interpolation
if (interpolation == true) {
//linear interpolation
// Normalize the time (i.e. make it a number from 0 to 1)
float normTime = (float) (System.currentTimeMillis() - starttime)/ (float) duration;
// Calculate the interpolated position of the bug
x = (int) (startx + ((float) (destx - startx) * normTime));
y = (int) (starty + ((float) (desty - starty) * normTime));
// If the difference between current time and start time has exceeded the duration
// then the animation/interpolation is over.
if ((System.currentTimeMillis() - starttime) >= duration) {
// Set interpolation to false
interpolation = false;
// Move the bug all the way to the destination
x = destx; y = desty;
}
//.
Flash over the years, has been used to prop up the regular browser like a sad old man drinking alone in a pub.
Today browsers come shipped with technology designed to rival flash and aim to shut it squarely out of the game.
Are browser ready to rock without Flash?
Sceneform SDK на практиці - UA Mobile 2019UA Mobile
Тема нативних движків, що спрощують роботу з 3D графікою для Android, є головним болем багатьох розробників. У той час як для iOS існує SceneKit, розробники під Android були змушені або йти в крос-платформені рішення (Unity3d, LibGDX і т.п.) або використовувати самописні/опенсорсні рішення з обмеженим функціоналом. Поява Sceneform SDK вирішує не тільки цю проблему але й інкапсулює в собі роботу з ArCore SDK, відкриваючи для розробників можливість нативної реалізації AR рішень, не вдаючись до стороннього SDK.
В рамках доповіді будуть розглянуті практичні можливості та обмеження Sceneform SDK стосовно проектів з доповненою реальністю (AR). Так само будуть розглянуті такі теми як SLAM, ArCore SDK, розпізнавання та трекінг маркерів на основі зображень, Cloud Anchors та існуючі альтернативи на ринку.
Sceneform SDK на практиці - UA Mobile 2019Eugene Kurko
Тема нативних движків, що спрощують роботу з 3D графікою для Android, є головним болем багатьох розробників. У той час як для iOS існує SceneKit, розробники під Android були змушені або йти в крос-платформені рішення (Unity3d, LibGDX і т.п.) або використовувати самописні/опенсорсні рішення з обмеженим функціоналом. Поява Sceneform SDK вирішує не тільки цю проблему але й інкапсулює в собі роботу з ArCore SDK, відкриваючи для розробників можливість нативної реалізації AR рішень, не вдаючись до стороннього SDK.
В рамках доповіді будуть розглянуті практичні можливості та обмеження Sceneform SDK стосовно проектів з доповненою реальністю (AR). Так само будуть розглянуті такі теми як SLAM, ArCore SDK, розпізнавання та трекінг маркерів на основі зображень, Cloud Anchors та існуючі альтернативи на ринку.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
Box2D and libGDX
1. Box2D
and
libGDX
Jussi
Pohjolainen
Tampere
University
of
Applied
Sciences
2. Box2D
• Free
open
source
2D
physics
simulator
engine
wriEen
in
C++
• Has
been
used
for
example
in
Angry
Birds,
Tiny
Wings
• Has
been
ported
to
Java,
Flash,
C#,
JavaScript
• Programs
that
use
Box2D
– libGDX,
Unity,
iOS
SpriteKit,
GameMaker
Studio
...
3. Concepts
• World
– CollecNon
of
bodies,
fixtures,
joints
that
interact
• Body
– Game
Objects
that
contains
fixtures
– Dynamic
(spaceship),
StaAc
(ground)
and
KinemaAc
– Fixture
• Body
has
Fixture!
• Density:
Mass
per
square
meter:
bowling
ball
dense,
balloon
not
• FricAon:
When
sliding
along
something,
amount
of
opposite
force
• ResAtuAon:
How
bouncy
object
is
(0
=
does
not
bounce,
1
=
very
bouncy)
• Shape
– Fixture
has
Shape
– Polygon
or
Circle,
can
be
mixed
• Joint
– Holds
bodies
together.
Several
joints
available.
4. World
Body
Fixture
Shape
// Create array full of bodies
Array<Body> bodies = new Array<Body>();
// Take all bodies from world and put them into array
world.getBodies(bodies);
// Get shape of first body, it's first fixture and it's shape
Shape s = bodies.get(0).getFixtureList().get(0).getShape();
5. Units
• Box2D
uses
floaAng
points
• Tuned
for
meter
–
kilogram
–
second
(KMS)
• OpNmized
so
that
shapes
can
move
between
0.1
–
10
meters
• It's
tempNng
to
use
pixel
as
units
-‐>
leads
to
poor
simulaNon
and
weird
behavior
– Keep
moving
objects
between
0.1
–
10
meters!
• DO
NOT
USE
PIXELS!
DO
NOT!
6. Units
in
libGDX
• Window/real
resoluNon
<-‐>
World
Units
<-‐>
Box2D
units
(meters)
• How
to
handle
this?
Just
use
meters
in
World
Units,
so
you
don't
have
to
make
any
conversions
– float width = 640.0f / 100.0f
– float height = 400.0f / 100.0f
– camera = new OrthographicCamera();
– camera.setToOrtho(false, width, height);
7. CreaNng
a
World
// Create world and set it's gravity!
// true => allow body sleeping
World world = new World(new Vector2(0,
-9.8f), true);
// Next steps: create a body to the world
8. Body
Types
• Dynamic
Body
– Player
and
other
actors
on
screen
• StaAc
Body
– Walls,
floors
and
so
on
• KinemaAc
Body
– Moving
pladorm
in
pladorm
game
– It's
a
staNc
body
that
can
also
move
and
rotate.
When
dynamic
body
collides,
kinemaNc
body
"wins"
9. Bodies
• Bodies
are
objects
in
physics
space
– Does
not
hold
texture!
So
it's
not
visible!
• Hold
properNes
like
– mass,
velocity,
locaNon,
angle
• Define
size
and
shape
of
the
body
using
a
fixture
• Shape
can
be
circle
or
polygon
or
a
mixture
of
these!
10. CreaNng
a
Body
• To
create
body,
use
– // Create BodyDef..
– Body playerBody = world.createBody(BodyDef);
• BodyDef?
– Type
of
body?
StaNc,
kinemaNc,
dynamic
– PosiNon
• Ager
creaNon,
add
a
Fixture
to
the
body
– Density,
ResNtuNon
(bouncy?),
fricNon
(slippery?),
shape
(circle
or
polygon)
– playerBody.createFixture(playerFixtureDef);
11. CreaNng
a
Body
public void createPlayerBody() {
// *** 1) DEFINITION OF A BODY *** /
// Body Definition
BodyDef myBodyDef = new BodyDef();
// It's a body that moves
myBodyDef.type = BodyDef.BodyType.DynamicBody;
// Initial position is centered up (width = 12.8, height = 7.2)
// This position is the CENTER of the shape!
myBodyDef.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
// *** 2) CREATE THE BODY *** /
Body playerBody = world.createBody(myBodyDef);
12. // *** 3) FIXTURE FOR THE BODY *** /
// Create fixture and add the shape to it
FixtureDef playerFixtureDef = new FixtureDef();
// Mass per square meter (kg^m2)
playerFixtureDef.density = 1;
// How bouncy object? Very bouncy [0,1]
playerFixtureDef.restitution = 1.0f;
// How slipper object? [0,1]
playerFixtureDef.friction = 0.5f;
// Create circle shape.
CircleShape circleshape = new CircleShape();
circleshape.setRadius(0.1f);
// Add the shape to the fixture
playerFixtureDef.shape = circleshape;
// Add fixture to the body
playerBody.createFixture(playerFixtureDef);
}
13. About
Rendering
• Box2D
holds
the
physics,
it's
not
about
rendering
– For
every
render
call,
update
(step)
the
world
• To
render,
map
some
texture
to
the
posiNon
of
the
playerBody!
• For
debugging,
use
debugRenderer
14. Example
About
Rendering
public class Box2DExample extends ApplicationAdapter {
private SpriteBatch batch;
public static final boolean DEBUG_PHYSICS = true;
public static final float WORLD_WIDTH = 6.4f;
public static final float WORLD_HEIGHT = 4.0f;
private OrthographicCamera camera;
private World world;
private Box2DDebugRenderer debugRenderer;
@Override
public void create () {
camera = new OrthographicCamera();
camera.setToOrtho(false, WORLD_WIDTH, WORLD_HEIGHT);
batch = new SpriteBatch();
world = new World(new Vector2(0f, -9.81f), true);
debugRenderer = new Box2DDebugRenderer();
createPlayerBody();
}
public void createPlayerBody() { ... }
@Override
public void render () {
batch.setProjectionMatrix(camera.combined);
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
if(DEBUG_PHYSICS) {
debugRenderer.render(world, camera.combined);
}
batch.begin();
// Do some drawing
batch.end();
world.step(1/60f, 6, 2);
}
}
16. Update
World:
Stepping
• To
update
world,
we
need
to
tell
the
world
to
step
// Advance simulation 1/60 of a sec. This should
// correspond to framerate in your game
float timeStep = 1/60.0f;
// How strongly to correct velocity when colliding
// More higher, more correct simulation but cost of performance
int velocityIterations = 6;
// How strongly to correct position when colliding
// More higher, more correct simulation but cost of performance
int positionIterations = 2;
world.step(timeStep, velocityIterations, positionIterations);
• Do
this
at
the
end
of
the
render()
call
17. Variable
Nmestep
• If
you
have
following
– world.step(1/60f, 6, 2);
• SimulaNon
can
be
ruined
if
machine
is
not
able
to
run
at
60fps
• You
could
calculate
the
game
speed
and
add
it
to
stepping
– world.step(framerate, 6, 2);
• Problem
now
is
that
your
game
can
run
very
very
fast
or
very
very
slow
18. public void render() {
...
doPhysicsStep();
}
private double accumulator = 0;
private double currentTime = TimeUtils.millis() / 1000.0;
private void doPhysicsStep() {
// We are not using Gdx.graphics.getDeltaTime(), it may not
// be accurate enough.
// Current time
double newTime = TimeUtils.millis() / 1000.0;
// How much time since last call?
double deltaTime = newTime - currentTime;
currentTime = newTime;
float TIME_STEP = 1/60f;
// If it took ages (> 0.25 => 4 fps)
// FIXED Upper limit to prevent going really slow
if(deltaTime > 0.25) {
deltaTime = 0.25;
}
accumulator += deltaTime;
while (accumulator >= TIME_STEP) {
world.step(TIME_STEP, 6, 2);
accumulator -= TIME_STEP;
}
}
19. "Ground"
public void createGround() {
// *** 1) DEFINITION OF A BODY *** /
// Body Definition
BodyDef myBodyDef = new BodyDef();
// This body won't move
myBodyDef.type = BodyDef.BodyType.StaticBody;
// Initial position is centered up
// This position is the CENTER of the shape!
myBodyDef.position.set(WORLD_WIDTH / 2, 0.25f);
// *** 2) CREATE THE BODY *** /
Body groundBody = world.createBody(myBodyDef);
// *** 3) FIXTURE FOR THE BODY *** /
// Create shape
PolygonShape groundBox = new PolygonShape();
// Real width and height is 2 X this!
groundBox.setAsBox( WORLD_WIDTH/2 , 0.25f);
// Add shape to fixture, 0.0f is density.
// Using method createFixture(Shape, density) no need
// to create FixtureDef object as on createPlayer!
groundBody.createFixture(groundBox, 0.0f);
}
20. Draw
texture
to
body
pos!
public void render() {
...
batch.draw(texture,
playerBody.getPosition().x,
playerBody.getPosition.y);
}
21. Draw
texture
to
body
pos!
batch.draw(playerTexture,
playerBody.getPosition().x - playerRadius,
playerBody.getPosition().y - playerRadius,
playerRadius, // originX
playerRadius, // originY
playerRadius * 2, // width
playerRadius * 2, // height
1.0f, // scaleX
1.0f, // scaleY
playerBody.getTransform().getRotation() * MathUtils.radiansToDegrees,
0, // Start drawing from x = 0
0, // Start drawing from y = 0
playerTexture.getWidth(), // End drawing x
playerTexture.getHeight(), // End drawing y
false, // flipX
false); // flipY
22. Create
Body
and
Add
User
Data
public void createJussi(float x, float y) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(x,y);
Body body = world.createBody(bodyDef);
PolygonShape dynamicCircle = new PolygonShape();
dynamicCircle.setAsBox(0.5f, 0.5f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.8f;
body.createFixture(fixtureDef);
// user data can be anything! any object!
body.setUserData(jussiTexture);
}
23. Create
Body
and
Add
User
Data
public void render() {
...
debugRenderer.render(world, camera.combined);
// populate the array with bodies
world.getBodies(bodies);
// iterate the bodies
for (Body body : bodies) {
if(body.getUserData() != null && body.getUserData() == jussiTexture) {
batch.draw((Texture) body.getUserData(),
body.getPosition().x - 0.5f,
body.getPosition().y - 0.5f,
...
body.getTransform().getRotation() * MathUtils.radiansToDegrees,
...
false
);
}
}
doPhysicsStep();
}
25. Forces
and
Impulses
• To
move
things
around,
you'll
need
to
apply
forces
or
impulses
to
a
body
• Force
– Gradually
over
Nme
change
velocity
of
a
body
– Also
angular
force
available,
torque
(twisNng
strength)
• Impulse
– Change
velocity
immediately
• Of
course
you
can
just
change
the
posiNon
of
a
body
26. Examples
// gradually accelerate right
body.applyForceToCenter(50f, 0, true);
// Jump up
body.applyLinearImpulse(new Vector2(0f, 20f),
body.getWorldCenter(),
true);