creating random torque and applied force question

1 reply [Last post]
mswallace
User offline. Last seen 30 weeks 3 days ago. Offline
Joined: 13 May 2010

I am hoping someone with a better understanding of the physics engin can give me a suggestion on my code. I have a game in Flash that I am porting to Corona. Basically an Astroids clone. I can't seem to get the random math correct to apply the correct force and torque to the astroids.

All the astroids seem to only move from left to right on the screen. The speed does very. It's more about the direction that I am trying to randomize.

Here is the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
local function createAstroids(  )
 
        for i=1, numberOfAstroidsForThisLevel()  do
                astroid = display.newImage("rock_large.png")
                astroid.x = (math.random() * ( 0- display.contentWidth)) + display.contentWidth
                astroid.y = 0 - (astroid.height - 2)
                
                astroid_group:insert(astroid)
 
                physics.addBody(astroid, {density=3})
        
                xforce = (math.random() * (0 - display.contentWidth)) + (display.contentWidth * 2)
                yforce = ( math.random() * (0 - display.contentHeight)) + (display.contentHeight * 2)
                atorque = (math.random() * -1000) + 1000
                
                xposition = (math.random() * (0 - astroid.x)) + (astroid.x * 2)
                yposition = (math.random() * (0 - astroid.y)) + (astroid.y * 2)
                
                astroid:applyForce(xforce,yforce, xposition, yposition)
                astroid:applyTorque(atorque)
        end
end

Here is the Flash version so that you get a sense of what I am going for. http://matthewsloanwallace.com/flixel-progress-flying-space-rocks-part-6

Replies

Matthew Pringle
User offline. Last seen 5 weeks 22 hours ago. Offline
Joined: 23 Feb 2010

something like below will pick a random angle, and with a set force work out the x and y components of the force

I think you would need to do an impulse rather than a force but it probably doesnt matter

1
2
3
4
5
6
7
8
local angle = math.random( 0 , 360 )
local sin = math.sin
local cos = math.cos
local pi = math.pi
local force = 0.7
local xFinal = ( sin( angle * pi / 180 ) * force )
local yFinal = ( cos( angle * pi / 180 ) * force )
 YOUROBJECT:applyForce( xFinal , -yFinal, YOUROBJECT.x, YOUROBJECT.y )

Viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.