Question by
reza74vi · Jan 18, 2020 at 02:47 PM ·
2d platformer
How to make rect transform work for ui image to make joystick?
I'm trying to make a joystick for android using ui image ,perviously i used event trigger component attached to inner circle(ui image).
Every thing worked fine until it detects a new touch on the screen then it ignores my pervius finger moving on joy stick and works according to the new finger.
So I decided to use this script instead but it works where ever i touch on the screen. I tried many ways and still I can't figure out where I am wrong.
Please help me with the simplest and easiest solution either for the first way or second way or both.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class joyStick : MonoBehaviour
{
private Vector3 pointA;
private Vector3 pointB;
public Vector3 offset;
public Vector2 bulletDirection;
private Vector2 myTouchPosition;
private Touch myTouch;
private int touchID;
private void Start()
{
pointA = transform.position;
bulletDirection = new Vector3(1f, 0f, 0f);
}
private void Update()
{
touchSelection();
if (myTouch.phase == TouchPhase.Moved && myTouch.fingerId == touchID)
{
myTouchPosition = myTouch.position;
pointB = new Vector3(myTouchPosition.x, myTouchPosition.y, Camera.main.transform.position.z);
offset = pointB - pointA;
bulletDirection = (pointB - pointA).normalized;
pointB = pointA + Vector3.ClampMagnitude(offset, 60);
offset.Normalize();
transform.position = pointB;
}
if (myTouch.phase == TouchPhase.Ended && myTouch.fingerId == touchID)
{
transform.position = pointA;
offset = Vector3.zero;
touchSelect = false;
}
}
private void touchSelection()
{
int i = 0;
while(i<Input.touchCount)
{
myTouch = Input.GetTouch(i);
myTouchPosition = myTouch.position;
if(myTouch.phase == TouchPhase.Began)
{
if (RectTransformUtility.RectangleContainsScreenPoint(GetComponent<RectTransform>(),myTouchPosition))
{
touchID = myTouch.fingerId;
}
}
++i;
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612221732im_/https://answers.unity.com/themes/thub/images/avi.jpg)