I’m a little bit confused on something within Codea. I am trying to get a ball to aim itself towards my touch (t.x). I’ve tried to use linearVelocity(the ball is a physics body) ,but when called, it flies in a completely opposite direction to my touch. Any advice on what I need to do?
@Staples Tap the screen or drag your finger around the screen.
displayMode(FULLSCREEN) function setup() b=physics.body(CIRCLE,20) b.x=WIDTH/2 b.y=HEIGHT/2 b.gravityScale=0 end function draw() background(40, 40, 50) fill(255) ellipse(b.x,b.y,40) end function touched(t) if t.state==BEGAN or t.state==MOVING then dx=t.x-b.x dy=t.y-b.y b.linearVelocity=vec2(dx,dy) end end
@Staples Here’s another version where the ball will stop at the last touched point.
displayMode(FULLSCREEN) function setup() b=physics.body(CIRCLE,20) b.x=WIDTH/2 b.y=HEIGHT/2 b.gravityScale=0 tx=b.x ty=b.y end function draw() background(40, 40, 50) fill(255) ellipse(b.x,b.y,40) dx=tx-b.x dy=ty-b.y b.linearVelocity=vec2(dx,dy) end function touched(t) if t.state==BEGAN or t.state==MOVING then tx=t.x ty=t.y end end
@dave1707 perfect, thanks. I was taking it that linearVelocity was forcing an object towards a certain vec2, but I now understand that it is basically the difference in direction from its current direction. Am I correct in saying this?
@Staples linearVelocity is the direction you want the object to go. If you want it to go left, then it would have a negative x velocity. To go right, it would have a positive x velocity. To go up, it has a positive y velocity. To go down, a negative y velocity. To go at some diagonal, the x,y velocities would be some x,y value positive or negative.
@Staples yes you do need to find the difference between two vectors for the linearVelocity. body1.linearVelocity = (body2.position - body1.position) will give the velocity of the direction towards body2’s position and (body1.position - body2.position) will give the direction facing away from body2, equally you can do (body2.position - body1.position)*-1 to give the direction facing away from body2.
If you already knew this then you know enough to make a good game.