# Touch repel

Hello, I’ve seen a couple of discussion on how to make a sprite go towards a touch but for my project i would like the sprite to move away from the touch. How would i do this and could you pleas comment it so i can understand it.
Also, it would be good if the sprite only moves when i am touching the screen.
Thx a lot.

Just try substituting in a couple negative values for the positive values in the discussion code

Example???

if x=3, y=-2 moves you toward, then x=-3, y=+2 moves you away

Can’t test the code but something like this should work using trig…

touch is your finger position, pt is the sprite’s position, speed is whatever value

``````dir = math.atan2(pt.y - touch.y, pt.x - touch.x)
pt.x = pt.x + math.cos(dir) * speed
pt.y = pt.y + math.sin(dir) * speed

``````

This will move the point away from the touch position.

@Xavier that trig is expensive. Wouldn’t it be simpler to do:

``````dir = pt - vec2(touch.x,touch.y)
pt = pt + dir:normalize() * speed
``````

Or even a one-liner:

``````pt = pt + (pt - vec2(touch.x,touch.y)):normalize() * speed
``````

Yar totally:D

@Klupa56 With the above variables, you would just need to have a vec2 called pt, a number called speed, put the code supplied in the touched function, and sprite an image at pt’s coordinates.

I’m a noob so sorry but i dont understand any of that

@Klupa56 - then maybe you need to learn some more about Lua and Codea first. The forum is here to solve problems, rather than teach you the language. Have a look at the wiki link above, there’s lots of good stuff there.

@Klupa56 I always found that the best way to learn was fiddling with code. Have a look a some codea example projects, you will learn a lot that way.

You can play around with the following (using vector math as shown by @LoopSpace .
At work so can’t test it, but this should run

``````
function setup()
pt = vec2(WIDTH/2, HEIGHT/2)
speed = 1
end

function draw()
sprite(img, pt.x, pt.y)
end

function touched(touch)
local dir = pt - vec2(touch.x,touch.y)
pt = pt + dir:normalize() * speed
end

``````

I’ve found over my past two weeks’ worth of working with vectors that they seem difficult, but really are not. First, scalars are what we think of as “normal numbers,” despite the fact that there really is no such thing. Vectors have an x value and a y value, and the length can be thought of as a line representing the hypotenuse of the triangle formed by two legs whose side lengths are that of the vector. Normalizing a vector, as I understand it, is the process by which one finds the hypotenuse, then divides the vector by that, thereby making the length of the resulting vector 1. This is useful for many things, and @LoopSpace does a good job describing them above. Also, as a side note, I learned the hard way that vectors can only be multiplied or divided by scalars. Half an hour’s worth of debugging spent on that

@TheSolderKing - I just did a post on vectors