- Home /
How to use the joystick to control the character
I have a question about use the joystick to control the character.
How to use the joystick to control the character?
I just can control the character by keyboard (use the "Input.GetAxis")
if I need to change it into the "Touch"(it means I have to use the GUIText to control the charater)
Chould teach how to do it or show me the script?
Thanks a lot.
Answer by DaveA · Mar 20, 2012 at 06:58 PM
I assume you have read this: http://unity3d.com/support/documentation/ScriptReference/Input.html especially this: http://unity3d.com/support/documentation/ScriptReference/Input.GetAxis.html but if you are asking how do do this with 'touch' on a mobile device? Look in Standard Assets (Mobile) for the joystick controls which put pictures of joystick on screen you can use like the real thing.
Answer by jbahr19 · Jul 10, 2015 at 08:37 AM
Alright after spending the better part of a day and half on trying to build my own joystick in the HUD (screen view canvas), I found this wonderful little bit of information (http://docs.unity3d.com/ScriptReference/Vector3.ClampMagnitude.html). However; applying that to a specific UI object was a tad difficult. Basically you have to define the component you want to move inside your HUD. For me I was trying to move an empty object with an child image to have an on-screen joystick.
The following code is what I got to work with my setup. Hope this helps!
using UnityEngine; using System.Collections;
public class SelectorMovement : MonoBehaviour {
public RectTransform rt;
public Vector3 centerPt;
public float radius;
void Start (){
rt = GetComponent<RectTransform> ();
centerPt = rt.anchoredPosition;
}
void Update() {
Vector3 position = new Vector3 (rt.anchoredPosition.x, rt.anchoredPosition.y, 0);
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0);
Vector3 newPos = position + movement;
Vector3 offset = newPos - centerPt;
rt.anchoredPosition = centerPt + Vector3.ClampMagnitude(offset, radius);
}
}
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
problems with virtual joystick for IOS 1 Answer
Getting Joystick Input from Matricom G-Pad BX? 0 Answers
Make Player face where Joystick is pointing? 6 Answers
How do I check what input device is currently beeing used? 4 Answers