- Home /
Question by
missingscenestudios · Oct 24, 2020 at 07:20 PM ·
mobileunity 2djoystickmobile devicesclamp
Show Joystick on the left part of the screen only
I made a joystick script and the joystick works perfectly(unity mobile) so the joystick shows up where you tap on the screen, but the problem is that is shows up anywhere on the screen, and I need it to show up on the left side only.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public Transform player;
private bool Touch;
private float speed = 10f;
private Vector2 A;
private Vector2 B;
public SpriteRenderer In2;
public SpriteRenderer Out2;
bool plsWork = false;
float pls;
public Transform Out;
public Transform In;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
A = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
Out.transform.position = A * 1;
In.transform.position = A * 1;
Out2.enabled = true;
In2.enabled = true;
}
if(Input.GetMouseButtonDown(0))
{
Debug.Log("check");
}
if (Input.GetMouseButton(0))
{
Touch = true;
B = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
}
else
{
Touch = false;
}
}
private void FixedUpdate()
{
if (Touch)
{
Vector2 offset = A - B;
Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
moveCharacter(direction * -1);
In.transform.position = new Vector2(A.x + -direction.x, A.y + -direction.y) * 1;
}
else
{
Out2.enabled = false;
In2.enabled = false;
}
}
void moveCharacter(Vector2 direction)
{
player.Translate(direction * speed * Time.deltaTime);
}
}
Comment
Answer by busedagidir · Oct 24, 2020 at 07:40 PM
You can use canvas for this. When you create a canvas in your hierarchy and in the inspector : "Canvas Scaler (Script) > UI Scale Mode choose "Scale with screen size and set x and y there. After that add that canvas a joystick image and set its position where ever you want. And final step you can add your script to this image I hope I could be able to undestand your question and help you :)