- Home /
Trying to track the direction of a swipe and then apply additional force to an object moving in that direction
I realize this question is probably ridiculously rudimentary, but this is literally the first batch of code I have written ever, in any language. After going through 2 or 3 coding and Unity3D books, I figured it was time to just sit down and start coding. Apologies in advance for my messy code and (probably) incorrect assumptions. I'll get it eventually :)
The gist of my prototype is I want to let the player swipe and object around the space, but I want the speed and thrust velocity to be controlled by a script. So, for instance, if the player swipes up, I want to get the normalized direction of the swipe, and then move the object in that direction. The catch is that I want the object to be powered by a motor that has nothing to do with the swipe speed or end position. So the script should grab the direction and say "Ok, I can move this object in that direction at the speed and power dictated in the script."
Hoping that makes sense, here is what I have so far. It is not complete, (the smash function is missing) but I wanted to know if I was on the right track
#pragma strict
var horizontalSpeed : float;
var verticalSpeed : float;
var thrust : float;
var thrustsRemaining : int;
var touch : Touch;
var direction : Vector2;
function Start () {
Init ();
}
function Init () {
thrustsRemaining = 2;
}
function Update () {
if (Input.touchCount == 2 && Input.GetTouch(0).phase == TouchPhase.Moved) {
touch = Input.touches[0];
CheckDirection ();
}
}
function CheckDirection () {
direction = touch.deltaPosition.normalized;
if (touch.TouchPhase.Began.y < touch.TouchPhase.Ended.y || touch.TouchPhase.Began.y == touch.TouchPhase.Ended.y) {
Thrust ();
} else if (touch.TouchPhase.Began.y > touch.TouchPhase.Ended.y) {
Smash ();
}
}
function Thrust () {
if (thrustsRemaining > 0) {
transform.Translate (touch.x * thrust * horizontalSpeed * verticalSpeed * touch.y * time.deltaTime)
thrustsRemaining--;
}
}
And yeah, I know that code is broken in more than one place. I'm fixing it as best I can. I was looking more for a point in the right direction, so to speak.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to drag a GameObject with touch but at a limited speed 1 Answer
Multi Touch Drag Screen To Move Player? 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer