Question by
laurenm · Apr 29, 2016 at 09:18 PM ·
scripting probleminput.touch
Dragging Pong paddles with touch?
I have created a simple pong game with 2 player paddles. I currently have keyboard inputs working to move each of them but i cannot seem to get my touch script to work for mobile use. I have looked at so many tutorials and still can't figure out what is wrong. I have it attached to an empty game object. Here is my code:
using UnityEngine; using System.Collections;
public class touchTest : MonoBehaviour {
public GameObject GO; //refer to GO that being dragged
public Vector2 GOcenter; //gameobjectcenter
public Vector2 touchPosition; //touch or click position
public Vector2 offset;//vector between touchpoint/mouseclick to object center
public Vector2 newGOCenter; //new center of gameObject
RaycastHit hit; //store hit object information
public bool touching = false;
// Use this for initialization
void Start()
{
}
void FixedUpdate()
{
foreach (Touch touch in Input.touches)
{
switch (touch.phase)
{
case TouchPhase.Began:
Ray ray = Camera.main.ScreenPointToRay(touch.position);
if (Physics.SphereCast(ray, 0.3f, out hit))
{
GO = hit.collider.gameObject;
GOcenter = gameObject.transform.position;
touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
offset = touchPosition - GOcenter;
touching = true;
}
break;
case TouchPhase.Moved:
if (touching == true)
{
touchPosition = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
newGOCenter = touchPosition - offset;
gameObject.transform.position = new Vector2(-20f, newGOCenter.y);
}
break;
case TouchPhase.Ended:
touching = false;
break;
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Problem when I call fonction with child class 1 Answer
Adding a Highscore to game 1 Answer
Help! Script won't work. 1 Answer