Hello,
I am currently trying to make rockets that fly towards a location, ultimately I want to have lots of these rockets being able to follow the current touch position. As a first step towards this I am trying to make a single rocket that tries to fly towards an ellipse in the centre of the screen. I am trying to make the rockets fly in a very fluid manner and to do natural looking turns. This is my attempt below, the issue is that the rocket turns very slowly and if I increase its turn angle the rocket ends up freaking out. Also have I used the rotate function correctly because sometimes I can’t tell if the rocket is turning about its centre?
Thanks!
--# Main
-- Rocket
displayMode(FULLSCREEN)
ROCKET_WIDTH = 10
ROCKET_HEIGHT = 30
TURN_ANGLE = 0.01
-- Use this function to perform your initial setup
function setup()
target = Target(WIDTH/2, HEIGHT/2,WIDTH*0.05)
rocket = Rocket(200,HEIGHT*0.1)
end
-- This function gets called once every frame
function draw()
background(200, 201, 212, 255)
target:draw()
rocket:draw()
rocket:update(target)
end
function touch()
target.touched(touch)
end
--# Rocket
Rocket = class()
function Rocket:init(x,y)
-- you can accept and set parameters here
self.pos = vec2(x,y)
self.vel = vec2(0,10)
self.angle = math.deg(math.atan(self.vel.x,self.vel.y))
print(self.angle)
self.speed = math.pow(((math.pow(self.vel.x,2))+ (math.pow(self.vel.y,2))),0.5)
print(self.speed)
self.speed = 10
self.vel = vec2(0,10)
end
function Rocket:draw()
pushMatrix()
pushStyle()
translate(self.pos.x + ROCKET_WIDTH/2,self.pos.y + ROCKET_HEIGHT/2)
rotate(-self.angle*10)
fill(255, 0, 229, 255)
stroke(255, 255, 255, 255)
rect(0,0,ROCKET_WIDTH,ROCKET_HEIGHT)
popStyle()
popMatrix()
end
function Rocket:update(target)
if target.y > self.pos.y then
if target.x > self.pos.x then
self.angle = self.angle + TURN_ANGLE
elseif target.x < self.pos.x then
self.angle = self.angle - TURN_ANGLE
end
end
if target.y < self.pos.y and target.x > self.pos.x then
self.angle = self.angle + TURN_ANGLE*2
elseif target.y < self.pos.y and target.x < self.pos.x then
self.angle = self.angle - TURN_ANGLE*2
end
self.vel = vec2(math.sin(self.angle),math.cos(self.angle))*self.speed
self.pos.x = self.pos.x + self.vel.x
self.pos.y = self.pos.y + self.vel.y
end
--# Target
Target = class()
function Target:init(x,y,radius)
-- you can accept and set parameters here
self.x = x
self.y = y
self.radius = radius
end
function Target:draw()
pushStyle()
fill(255, 255, 255, 255)
ellipse(self.x,self.y,self.radius)
-- Codea does not automatically call this method
popStyle()
end
function Target:touched(touch)
-- Codea does not automatically call this method
self.x = CurrentTouch.x
self.y = CurrentTouch.y
end