- Home /
Flick ball in 3D
Hi, I am trying to create a mobile game where the user can shoot a ball at a target, by flicking the screen, in 3D.
So far I have managed to move the ball based on the users "flick" including the power of the flick, However the ball only moves up/down and sideways. I want the ball to move more "forward" than up.
In the picture included, the top diagram illustrates the current behaviour, and the bottom diagram illustrates what the movement I am trying to achieve:
the green arrows in the diagram are the users input and the red arrows are the ball movement.
I have had to swap between the y and z axis because of other aspects of the game
This is the code I am using (from: ): using UnityEngine; using System.Collections;
public class TouchMonitor : MonoBehaviour {
public Rigidbody ball;
private Vector3 touchStart;
private Vector3 touchEnd;
private GameObject lineRenderer;
void Update () {
if (Input.touchCount > 0)
{
Touch t = Input.touches[0];
if (t.phase == TouchPhase.Began)
{
touchStart = t.position;
}
if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
{
touchEnd = t.position;
DoInput();
}
}
if (Input.GetButtonDown("Fire1"))
{
touchStart = Input.mousePosition;
}
if (Input.GetButtonUp("Fire1"))
{
touchEnd = Input.mousePosition;
DoInput();
}
}
void DoInput()
{
Vector3 p1 = new Vector3();
Vector3 p2 = new Vector3();
touchStart.z = Camera.main.nearClipPlane+.1f; //push it a little passed the clip plane for camera, just to make sure its visible on screen
touchEnd.z = Camera.main.nearClipPlane+.1f;
p1 = Camera.main.ScreenToWorldPoint(touchStart);
p2 = Camera.main.ScreenToWorldPoint(touchEnd);
CreateLine(p1,p2);
Vector3 v = p2-p1;
//v.Normalize();
ball.AddForce(v*500, ForceMode.Impulse);
}
//creates an ugly purple line from pos1 to pos2 in worldspace
void CreateLine(Vector3 p1, Vector3 p2)
{
Destroy(lineRenderer);
lineRenderer = new GameObject();
lineRenderer.name = "LineRenderer";
LineRenderer lr = (LineRenderer)lineRenderer.AddComponent(typeof(LineRenderer));
lr.SetVertexCount(2);
lr.SetWidth(0.001f, 0.001f);
lr.SetPosition(0, p1);
lr.SetPosition(1, p2);
}
}
and to swap between the axis:
using UnityEngine;
using System.Collections;
public class Gravity : MonoBehaviour {
private Vector3 gravity;
// Use this for initialization
void Start () {
gravity = Physics.gravity;
}
// Update is called once per frame
void Update () {
gravity.x = 0;
gravity.y = 0;
gravity.z = -20;
Debug.Log("Gravity Z");
Physics.gravity = gravity;
}
}
This is my first attempt at creating a game and I am learning as I go along. Any suggestions would be greatly appreciated!
hey did u completed this logic of swiping the ball in 3d.. plz do reply man need a help