I've been searching for a solution for my problem for a while on the web, but i didn't find anything that work properly
What i want to do
I have a bouncing ball and I want to let the user flick it with his finger (using a swipe gesture or whatever). The ball shouldn't start moving unless the player flick touch the ball. I don't want the ball to move if the player flicks anywhere on the screen, only if the flick touch the ball
What i've done so far :
I've tried to write a script which would detect the touch starting position and the touch end position, and check if the end position is the same as the ball position to make sure that the flick touch the ball. Then the script calculate the direction vector by substrating the start position from the end position.
After that i use the AddForce
methode and give it the direction vector as a parameter.
Here's my code, (it's better than 1000 words ) :
using UnityEngine;
using System.Collections;
public class Movement : MonoBehaviour
{
public Vector2 start;
public Vector2 end;
public Vector2 direction;
public Vector2 ballPos;
public float Flicktime;
void Start(){
}
void Update(){
ballPos = new Vector2(transform.position.x,transform.position.y);
if (Input.touchCount > 0)
{
Touch t = Input.touches[0];
if (t.phase == TouchPhase.Began)
{
start = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
}
if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
{
end = Camera.main.ScreenToWorldPoint(new Vector3(t.position.x,t.position.y,0));
direction = end-start ;
if(t.position == ballPos){
rigidbody2D.velocity = direction * 2 ;
}
}
}
}
}
What's the problem ?
The problem is that the code doesn't work.
When i launch the game in the Unity Remote 4 app in my android device and try to flick the ball it doesn't move, the inspector shows that the the scripte is calculating the start & end positions and the direction vector, but the ball doesn't move, it stays in the same position even when the flick touch the ball.
So what's the problem ? is there a better way to do it ?
Since the ball have a circle collider how to make it detect collision with the player swipe ?
Thank's and have a nice weekend !