Here’s some sample code
display.setStatusBar( display.HiddenStatusBar )
local physics = require "physics"
physics.start()
physics.setDrawMode ( "normal" )
physics.setGravity( 0, 0 )
local enemy1 = display.newRect( 70, 50, 25, 25)
enemy1:setFillColor(255,0,0)
physics.addBody( enemy1, "dynamic", {isSensor = true} )
local player = display.newRect( 150, 150, 50, 50 )
physics.addBody( player, "dynamic" )
player.myName = "player"
player.isFixedRotation = true
local function movePlayer( event )
movetx = event.x - player.x
movety = event.y - player.y
vmax = 100
moves = (movetx\*movetx + movety\*movety)
sfactor = (vmax^2/moves)^0.5
velx = movetx \* sfactor
vely = movety \* sfactor
player:setLinearVelocity(velx\*3, vely\*3);
if event.phase == 'ended' then
player:setLinearVelocity(0, 0)
end
end
Runtime:addEventListener( "touch", movePlayer )
local function moveEnemy( event )
gox = player.x - enemy1.x
goy = player.y - enemy1.y
if gox \< 50 then
gox = gox \* 2
end
if goy \< 50 then
goy = goy \* 2
end
if gox \> 200 then
gox = 200
end
if goy \> 200 then
goy = 200
end
if gox \< -200 then
gox = -200
end
if goy \< -200 then
goy = -200
end
enemy1:setLinearVelocity(gox, goy)
if event.phase == "ended" then
enemy1:setLinearVelocity( 0, 0)
end
end
Runtime:addEventListener( "enterFrame", moveEnemy )
Unfortunately it’s no good, as in not perfect. When the enemy gets closer to the player it slows down for a few reasons. It annoyed me that it didn’t work so I remade the code again. Try both whichever is best feel free to use
[code]
display.setStatusBar( display.HiddenStatusBar )
local physics = require “physics”
physics.start()
physics.setDrawMode ( “normal” )
physics.setGravity( 0, 0 )
local enemy1 = display.newRect( 70, 50, 25, 25)
enemy1:setFillColor(255,0,0)
physics.addBody( enemy1, “dynamic”, {isSensor = true} )
local player = display.newRect( 150, 150, 50, 50 )
physics.addBody( player, “dynamic” )
player.myName = “player”
player.isFixedRotation = true
local function movePlayer( event )
movetx = event.x - player.x
movety = event.y - player.y
vmax = 100
moves = (movetx*movetx + movety*movety)
sfactor = (vmax^2/moves)^0.5
velx = movetx * sfactor
vely = movety * sfactor
player:setLinearVelocity(velx*3, vely*3);
if event.phase == ‘ended’ then
player:setLinearVelocity(0, 0)
end
end
Runtime:addEventListener( “touch”, movePlayer )
local function moveEnemy( event )
gox = player.x - enemy1.x
goy = player.y - enemy1.y
if gox > 0 then
testx = 100
end
if gox < 0 then
testx = -100
end
if goy > 0 then
testy = 100
elseif goy < 0 then
testy = -100
end
enemy1:setLinearVelocity(testx, testy)
if gox < 10 then
enemy1:setLinearVelocity(textx, testy)
end
if gox < -10 then
enemy1:setLinearVelocity(testx, testy)
end
end
Runtime:addEventListener( “enterFrame”, moveEnemy )
[/code] [import]uid: 77199 topic_id: 24945 reply_id: 101448[/import]