- Home /
EARTH CALLING ANSWER!!!!
I am making a 2d game. I have an object, that I want to move by swiping. But I want to move in the direction of the swipe (not to the swipe).
I have a script but it doesn't work, because I don't know how, in javascript, to calculate the overall direction of a swipe and make my player move in that direction.
What is the best way to move parallel to a swipe's direction in 2D space?
Thanks for any answers!
Take the starting point and ending point of the swipe and make it a vector. Then you can use it to move your object.
To make the vector simply get the differences between each x,y and z and store them in a Vector3.
@fafase: Thanks for the suggestion, this we tried a while ago and for some reason didn't work.
Cheers for the help though!
Answer by MithosAnnar · Apr 06, 2012 at 12:01 PM
We solved it!
Here is the script for anyone who is interested!
var myTransform : Transform;
var mousePositionStart : Vector3;
var mousePositionEnd : Vector3;
var direction : Vector3;
var move : boolean = false;
var speed : float = 500;
function Update () {
myTransform.position.z = - 0.5;
rigidbody.velocity = direction * Time.deltaTime * speed;
if (Input.GetMouseButtonDown(0)) {
mousePositionStart = Input.mousePosition;
}
if (Input.GetMouseButtonUp(0)) {
mousePositionEnd = Input.mousePosition;
if (mousePositionEnd.sqrMagnitude >= mousePositionStart.sqrMagnitude ||
mousePositionEnd.sqrMagnitude <= mousePositionStart.sqrMagnitude) {
move = true;
}
if (move == true) {
direction = vector3(mousePositionStart, mousePositionEnd);
move = false;
}
}
}
function vector3 (from : Vector3, to : Vector3) {
return (to - from).normalized;
}
Thank you, unity forum!!
Your answer
![](https://koobas.hobune.stream/wayback/20220613070004im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Touch movement not working 1 Answer
4 way direction movement using a Character Controller. 1 Answer
Character rotating to previous rotation 1 Answer
How do I keep my character facing the direction of travel after movement stops? 1 Answer
tranform.TransformDirection not effecting spawned object 2 Answers