LECTURE 9Announcements
Congrats!• You are done with all
the assignments in this class!
• From now on everything you work on is designed by you
• Good work so far!
Final Coding• Time to start coding
for your final project• Remember, you should
be mostly finishing your engine this week
• Don’t forget to set up a meeting with your mentor TA soon
QUESTIONS?Announcements
LECTURE 9Collision Detection III
Point of Collision• We want to find out
where shapes hit• In our simulation,
colliding shapes are intersecting– Generally the intersection
is small– So we choose a point that
approximately represents where the intersection is
Poly-Poly• When two polygons
(AABs are polygons too!) collide, at least one vertex of one shape is inside the other– If there’s only one point,
use that as the point of collision
– If there’s more than one, average them!
Circle-Circle• Circle-Circle is easy:– It’s on the line
connecting the centers, with ratio of the radii
• Remember this is in world (absolute) coordinates
�⃗�1
�⃗�2
Circle-Poly• If vertices of the poly
are within the circle, then average them
• If not, then take the point along the MTV:
• (Depends on MTV direction)
QUESTIONS?Collision Detection III
LECTURE 9Physics III
ROTATIONPhysics III
Rotation• We currently have
shapes that don’t rotate
• First step is to be able to rotate shapes
• Next step is to provide collision response for rotating entities
Terminology• Let’s define some
things:• Angle, θ (CCW)• Angular velocity, ω• Angular acceleration, α• Moment of Inertia, – Analogous to mass
(inertia) for rotation
θω
Basics• Your physical entities
should have an angle, angular velocity, and angular acceleration
• You should integrate these as before
• But whenever you do this you have to physically rotate the shape
public class PhysicalEntity{ float angle, aVel, aAcc;
void move(float time) { //integrate position aVel += aAcc*time; angle += aVel*time; aAcc = 0; rotate(aVel*time); }}
Rotating Shapes• What shapes do we need to rotate?• AAB doesn’t rotate, by definition• Circles are circles– You still need angular values for the circle
though, what if the hitbox is a circle?
• Therefore only polygons need to rotate• Rotate polygons by rotating their vertices
Centroid of Polygon• Every shape rotates around its centroid• The centroid of a polygon with vertices is:
• Where • and are coordinates of vertices in CCW
order
Rotating Polygons• To rotate a polygon, rotate
each vertex by the angle
• These vectors are the vertices relative to the centroid!
• Remember to update edges as well
θ𝑣0′
Inertia• We also need the moment of inertia of an
object• You can define or calculate it• Circle: • Polygon:
QUESTIONS?Rotation
ROTATIONAL PHYSICSPhysics III
Impulse and Forces• How can we cause
shapes to rotate in the world?
• Currently we are applying impulse/forces the centroids of entities
• Apply impulse/force to object, but not at centroid
Impulse and Forces• Now your impulses and
forces have a magnitude and a point of application
• is relative to the centroid• The magnitude is
actually a vector• for impulse and for
force from now on
𝑟 or
Angular Impulse and Forces
• In relation with angular velocity and acceleration:
or
𝑟
Collision Response• We need to change
the impulse we calculated in Physics II
• It’s now a different value that is applied at some specific point– It’s applied to the point
of collision!
Some Definitions• More definitions:• , are the vectors from
the centroids of the shapes to the collision point
• , are the perpendiculars to ,
• is the normalized MTV
𝑟𝑎
𝑟𝑏
𝑟𝑏⊥
𝑟𝑎⊥
�̂�
Collision Response• Magnitude of the impulse
• , are projections of velocities onto the • The impulse is in the direction of ,
determine the sign based on your MTV direction
Fixed Rotation• Just like with static shapes, there should also
be shapes that don’t rotate• Just like with the previous impulse equation,
have a special case for non-rotating objects• Replace with if the entity doesn’t rotate• Note that if both objects don’t rotate, the
equation reduces to the old equation
QUESTIONS?Rotational Physics
FRICTIONPhysics III
Friction• We don’t want
everything to be slippery– Friction slows things
down
• Give every physical entity a friction value greater than 0
Frictional Force• The frictional force is
parallel to the surface of contact– i.e. perpendicular to
MTV
• The direction is determined by the direction of the relative velocity (1D):
a
b
a
b
�⃗�𝑡𝑣
𝐹 𝑓𝑟𝑖𝑐𝑡𝑖𝑜𝑛
−𝐹 𝑓𝑟𝑖𝑐𝑡𝑖𝑜𝑛
Relative Velocity• Only velocity
perpendicular to the MTV is relevant
• Direction of the perpendicular () doesn’t matter– Consistency matters
�⃗�𝑎
�⃗�𝑏
�̂�⊥
How Much Force?• From physics, the
friction force on object A due to object B is proportional to the force exerted on object A by object B
• We don’t really have that force…– But we did apply impulse
to the objects!
�⃗� 𝑛𝑜𝑟𝑚𝑎𝑙
𝑣
𝑘 �⃗�𝑛𝑜𝑟𝑚𝑎𝑙
The Force• So we have
• is the impulse applied in collision response
• is a constant
�⃗�𝑎
�⃗�𝑏
�̂�⊥
�⃗�
− �⃗�
Disclaimer• This friction works for
the case when the relative velocity is linear
• With rotation, things become much more difficult
• If you want to combine these, good luck!
ω
𝑢𝑟𝑒𝑙=?�⃗�
QUESTIONS?Friction
LECTURE 9Networking
NETWORKING STRATEGIESNetworking
The Illusion• All players are
playing in realtime on the same machine
• But of course this isn’t possible
• We need to emulate this as much as possible
Send the Entire World!• Players take turns
modifying the game world and pass it back and forth
• Works alright for turn-based games
• …but usually it’s bad– RTS: there are a million units– FPS: there are a million
players– Fighter: timing is crucial
Send Commands• Each player sends the other
all actions that alter shared game world
• “Deterministic P2P Lockstep”• Problem: everything must
evaluate the same– Or else there are desyncs
• Problem: have to wait for all the other players’ commands– So everyone is limited by
laggiest player
Player 1State 1
processP1Inputs()sendReceiveInputs()
processP2Inputs()
State 2
Player 2State 1
sendReceiveInputs()processP1Inputs()processP2Inputs()
State 2
Client-Server Model• One player is the
authoritative server• Other player is a “dumb
terminal”– Sends all input to server– Server updates the world
and sends it back
• Problem: client has to wait for server to respond to perform even basic actions
Player 1 (server)State 1
processP1Inputs()processP2Inputs()
sendState()
State 2
Player 2 (client)State 1
sendInputs()
receiveState()
State 2
Client-side Prediction• Client responds to
player input immediately
• When the server sends back the authoritative game state, client state is overwritten
ServerState 1
processP1Inputs()processP2Inputs()
sendState()
State 2
ClientState 1
sendInputs()processP2Inputs()
receiveState()
State 2
Rollback• But the server just sent a state that was
100ms in the past!• What if games have diverged since then?
– For instance, both players think they’ve collected a single powerup
• Client has to roll back the world and integrate commands since the last known good state
Masking the Timewarp• Problem: laggy players
experience this jump often
• Solution: if the server usually sends states from 100ms ago, run the client 100ms behind
• Turns a jumpy experience into a smooth, only slightly slow one
QUESTIONS?Networking Strategies
IMPLEMENTATIONNetworking
TCP: Transmission Control Protocol
• Abstracts over IP• All packets are
guaranteed to be received and in the correct order
• Good for sending important, permanent data (websites, databases, etc)
UDP: User Datagram Protocol
• A very thin shell around IP
• Much faster than TCP, but no guarantees about reception or order
• Good for information where only the most recent state matters (streaming, etc)
TCP vs UDP• Most action games use
UDP and most turn-based games use TCP
• Can potentially combine them– TCP sends important data,
UDP sends timely data
• Best choice varies by project– (for naïve version, TCP is
fine)
Java Sockets• Very good for most
purposes• Read and write
objects to sockets• UDP is deprecated
for sockets; for UDP use DatagramSocket
Settings Up Sockets• Open a connection on a
port• Open an input/output
stream from the socket• Read and write to the
streams (which use the socket’s protocol)
• Close the streams and sockets
String host = “127.0.0.1”;int port = 10800;Socket out = new Socket(ip, port);ObjectOutputStream stream;stream = new ObjectOutputStream( out.getStream());stream.writeObject(“HelloWorld”);stream.close();out.close();
String host = “127.0.0.1”;int port = 10800;Socket in = new Socket(ip, port);ObjectInputStream stream;stream = new ObjectInputStream( in.getStream());System.out.println(
stream.readObject());stream.close();in.close();
Edge Cases• What if…
– The client disconnects– The server dies– The client goes insane and
sends gibberish– The client loses internet for
30 seconds– The client is malicious– The client changes IP
address
• Handling errors well is vital to player experience
Elegant Disconnects• Handle and respond to IO
exceptions– Don’t just dump a stack trace
• Display informative status messages
• Send heartbeat packets every few seconds– Then respond if server/client
hasn’t received a heartbeat in a while
• Never let the game continue to run in an unrecoverable state!
QUESTIONS?Networking
LECTURE 9Tips for Final 1
JAVA TIP OF THE WEEKTips for Final 1
Breaking is Awkward• Let’s say we have
nested loops• A break will only
escape the innermost loop
• So we normally need some dumb boolean to keep track
// find the first occurrence of 0int row, col;boolean found = false; for (row=0; row<rows; row++) { for (col=0; col<cols; col++) { if (data[row][col] == 0) { found = true; break; } } if (found) { break; }}
Introducing Labeled Breaks• Code blocks can be
labeled• A break can be
made to escape to a certain labeled block
• Can also use this strategy with a continue
// find the first occurrence of 0int row, col;search:for (row=0; row<rows; row++) { for (col=0; col<cols; col++) { if (data[row][col] == 0) { break search; } }}
Other Fun Stuff• Arbitrary blocks of
code can be labeled• Therefore you can
have an arbitrary break
• Whee! It’s like a goto!– But don’t use it like one– Can’t jump forwards,
either
myLittleGoto: { // whatever code blah blah if (check) { break myLittleGoto; } return;}
// execution ends up here if// check is true!
QUESTIONS?Tips for Final 1
M4 PLAYTESTING!Last class playtesting!