- Home /
Method for giving a ball momentum through a swipe
Hi I am working on a project where the user needs to flick a ball to give it movement. At the moment I have this code working. A quick summary of how it works: Takes the initial location of your mouse cursor OnMouseDown and as you drag it provides an updating end location as a direction to apply a force to by using AddForce. To test this script just add it to a Ball with a ridgidBody and make sure that the camera perspective is set to orthographic.
#pragma strict
var hit: RaycastHit;
var startPoint: Vector3;
var endPoint: Vector3;
var mousePosition: Vector3;
var updateTimer: boolean;
var flickTimer: float;
var dragTimer: float = 0.2;
var onBall: boolean;
var strength: float;
function OnMouseDown()
{
updateTimer = true;
var temp: Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
startPoint = Vector3(temp.x ,temp.y, 0);
}
function OnMouseDrag()
{
var temp: Vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
endPoint = Vector3(temp.x ,temp.y, 0);
if(updateTimer)
{
flickTimer += Time.deltaTime;
}
}
function OnMouseUp()
{
flickTimer = 0;
updateTimer = false;
}
function FixedUpdate()
{
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var checkBall = Ray(mousePosition, Vector3(0,0,5));
Debug.DrawRay(mousePosition , Vector3(0,0,5), Color.red);
onBall = false;
if(Physics.Raycast(checkBall, hit, 5))
{
Debug.DrawRay(mousePosition , Vector3(0,0,5), Color.red);
if(hit.collider.tag == "Ball" )
{
onBall = true;
}
}
if(flickTimer < dragTimer && updateTimer == true && onBall == false)
{
var temp: Vector3 = Vector3(endPoint.x - startPoint.x, endPoint.y - startPoint.y, 0);
GetComponent.<Rigidbody>().AddForce(temp*strength, ForceMode.Force);
Debug.DrawRay(startPoint, endPoint, Color.cyan);
}
}
Im not sure if this is the best method to give a ball momentum using a flick or a swipe gesture. I had another idea of where the swipe would record locations and create a "path" and apply addForce at each point in relation the next. If you have any other methods that may prove a bit more natural or work better in general any advice is greatly appreciated.