- Home /
How do I make the center of the joystick bounce back to the middle when its not being used?,
I am new to this whole creator thing with c#, I can get my players to move however I want, but the center of the joystick does not re center after I use it which is bothersome. How can I accomplish this? I tried looking up guides but everyone is so different with how they write script I can't find a good solution that works with mine. Id also like to figure out how to fix the joystick in one spot instead of it following my finger around. Thanks! Here is the code I have.
using UnityEngine;
public class JoystickA : MonoBehaviour {
public Transform player;
public float speed = 5.0f;
private bool touchStart = false;
private Vector2 pointA;
private Vector2 pointB;
public Transform circle;
public Transform outerCircle;
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
circle.transform.position = pointA * -1;
outerCircle.transform.position = pointA * 1;
circle.GetComponent<SpriteRenderer>().enabled = true;
outerCircle.GetComponent<SpriteRenderer>().enabled = true;
}
if (Input.GetMouseButton(0))
{
touchStart = true;
pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
}
else
{
touchStart = false;
}
}
private void FixedUpdate()
{
if (touchStart)
{
Vector2 offset = pointB - pointA;
Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
moveCharacter(direction * 1);
circle.transform.position = new Vector2(pointA.x + direction.x, pointA.y + direction.y) * 1;
}
else
{
circle.GetComponent<SpriteRenderer>().enabled = false;
outerCircle.GetComponent<SpriteRenderer>().enabled = false;
}
}
void moveCharacter(Vector2 direction)
{
player.Translate(direction * speed * Time.deltaTime);
}
},
Your answer
Follow this Question
Related Questions
Change the position of the Joystick by tap 2 Answers
how to shoot with joystick 0 Answers
why is my character rotation always 180° after joystick is released. 1 Answer
Mobile joystick not moving player 0 Answers
mobile joystick 1 Answer