Hi, kind folks, i have some problem with rotating object on the screen. I will try explain my problem clearly.
I have one rectangle on the screen (more precisely png image) and i need rotate it accordingly player touches. I used angleBetween() func, but it not so accurately (or i misunderstand this func). There is my class and screenshots:
Lasers = class()
function Lasers:init()
-- you can accept and set parameters here
self.laserx = WIDTH/2+20
self.lasery = 130
self.angle = 0
self.vec = vec2(WIDTH/2,0)
end
function Lasers:draw()
-- Codea does not automatically call this method
self.angle = math.deg(self.vec:angleBetween(vec2(CurrentTouch.x,CurrentTouch.y)))
pushMatrix()
translate(self.laserx,self.lasery)
if CurrentTouch.x < WIDTH/2 then
rotate(-self.angle)
else
rotate(self.angle)
end
print(self.angle)
sprite("Documents:Laser",0,0,1024/6,768/6)
popMatrix()
end
@lupino8211 Try this.
displayMode(FULLSCREEN)
function setup()
rectMode(CORNER)
angle=0 -- angle
lx=300 -- laser x
ly=100 -- laser y
end
function draw()
background(0)
fill(255)
sprite("Platformer Art:Hill Tall",300,100)
pushMatrix()
translate(lx,ly)
rotate(angle)
rect(0,0,100,10)
popMatrix()
end
function touched(t)
if t.state==BEGAN then
angle=math.deg(math.atan2(t.y-ly,t.x-lx))
end
end
@dave1707 thank you very much!
If you look carefully at the screen, the direction that the laser is pointing in is parallel to the line joining the lower-left of the screen to the point where you touch. That’s because the self.vec:angleBetween(CurrentTouch.x,CurrentTouch.y)
computes the angle subtended at the origin which is the lower-left of the screen. What Dave’s code does is relocate that to the pivot of the laser arm.
Here’s the code above, but using angleBetween instead of atan2. I’m not sure if one has an advantage over the other. I also added code for a bullet.
displayMode(FULLSCREEN)
function setup()
angle=0 -- angle
lx=300 -- laser x
ly=100 -- laser y
ex=-5
ey=-5
dir=vec2(0,0)
end
function draw()
background(0)
sprite("Platformer Art:Hill Tall",300,100)
pushMatrix()
translate(lx,ly)
rotate(angle)
rect(0,-5,100,10)
popMatrix()
ex=ex+dir.x*10
ey=ey+dir.y*10
fill(255)
ellipse(ex,ey,8)
end
function touched(t)
if t.state==BEGAN then
angle=math.deg(vec2(0,0):angleBetween(vec2(t.x-lx,t.y-ly)))
v1=vec2(t.x-lx,t.y-ly)
dir=v1:normalize()
ex=lx
ey=ly
end
end
@LoopSpace thank you for explanation , and @Dave1707 thank you for another example