Jump to content


Get speed of physics2d object

Recommended Posts

Hi there,


I am working on a game that uses Greensocks Physics2d plug-in. I have the object being tweened rebounding off other objects.

I need to be able to get the speed of the tweened movieclip at any time. Is there a way to do this that is not processor heavy.


My tween looks like this:-


TweenMax.to(ball, 20, {physics2D:{velocity:storeVelocity, angle:pingArrow._rotation, gravity:gravity}, onUpdate:doChecks, motionBlur:{strength:mBStrength, quality:mBQuality}});


I set the velocity but obviously the speed decreases over time and depending on the angle it flies.





Link to comment
Share on other sites

There are two options I can think of:


1) Use the variables you set in the tween and the tween's currentTime to figure it out. Here's a long-hand version that you could easily consolidate and streamline for performance, but I wanted to make the concept clear:


var tween:TweenLite = TweenLite.to(mc3, 3, {physics2D:{angle:-45, velocity:100, gravity:200}, onUpdate:report});
function report():void {
var angle:Number = tween.vars.physics2D.angle * Math.PI / 180; //in radians
var initialVelocity:Number = tween.vars.physics2D.velocity;
var initialVelocityX:Number = Math.cos(angle) * initialVelocity;
var initialVelocityY:Number = Math.sin(angle) * initialVelocity;
var ay:Number = tween.vars.physics2D.gravity; //acceleration on the y-axis
var ax:Number = 0; //acceleration on the x-axis. Zero because gravity is straight down - no acceleration on the x-axis
var time:Number = tween.currentTime; //number of seconds that have elapsed.

var vx:Number = initialVelocityX + (ax * time);
var vy:Number = initialVelocityY + (ay * time);
var speed:Number = Math.sqrt(vx * vx + vy * vy);
trace("y-axis velocity: "+vy+", x-axis velocity: "+vx+", overall current speed: "+speed);


2) Add code in your onUpdate that would record the current position and compare it to the previous position and check the time as well (getTimer()) to figure out how much time has elapsed and the distance between the previous and current position. Deduce the velocity from that.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.