- Home /
Touch Controls for a 2D ball game
I need some help for my test app, I just cant implement the right touch input methode to move the ball instead of the camera.
I have ball which is a prefab and gets cloned every second. I attached touch controls to the main camera with Raycast2D but it moves only the camera, not the ball which has a Rigidbody2D and a Collider2D. When I attach the touch controls to the ball prefab, it works, but it will move all ball game objects, not only the one which I touched. I tried several touch scripts, non of them suited for my game. Does someone have a script which will work for my ball game (attaching it to the main camera but only moving the ball I touched, not every ball - Rigidbody2D / Collider2D)?
I used this script first, it worked like I described above: // Moves object according to finger movement on the screen
var speed : float = 0.1;
function Update () {
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Moved) {
// Get movement of the finger since last frame
var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;
// Move object across XY plane
transform.Translate (-touchDeltaPosition.x * speed,
-touchDeltaPosition.y * speed, 0);
}
}
I also used the other ones from here. I tried to "mix" them to suit my style but failed.
My code looks like this now:
using UnityEngine;
using System.Collections;
public class TouchTest2 : MonoBehaviour
{
public float moveSpeed = 0.1F;
private RaycastHit2D hit;
void FixedUpdate ()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
{
hit = Physics2D.Raycast(camera.ScreenToWorldPoint(Input.GetTouch(0).position), Vector2.zero);
if(hit != null && hit.transform != null)
{
Debug.Log(hit.transform.name);
Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
rigidbody2D.AddForce(new Vector2(-touchDeltaPosition.x * moveSpeed, -touchDeltaPosition.y * moveSpeed));
}
}
}
}
When I start the game I get the error that the main camera needs to have a Rigidbody2D attached to it but that doesnt make sense since I only want to move objects with Rigidbody2D (and Collider2D), not the camera. Anyone with a solution for my problem?
Anyone please who can help me out? If there is a similar script available, can you post it here or the link where I can find it? $$anonymous$$aybe I need to change only some code to work with the script I made?