- Home /
direction of joystick to control my character movements
im using NavMesh to control my character movements i set a target which the character will follow but now i only can move in the horizontal and vertical axis but not the diagonal axis here is my javascript i currently have;
private var joystickObj : GameObject;
private var joystick : Joystick;
var target : Transform;// Set target forn player to move to
var agent : NavMeshAgent;
function Start() {
joystickObj = GameObject.Find("Single Joystick");
joystick = joystickObj.GetComponent(Joystick);
agent = GetComponent(NavMeshAgent);
}
function Update() {
if (joystick.position.x > .5) {
target.position = Vector3(transform.position.x + 2,transform.position.y,transform.position.z);
Debug.Log("moveright");
}
else if (joystick.position.x < -.5) {
target.position = Vector3(transform.position.x - 2,transform.position.y,transform.position.z);
Debug.Log("moveleft");
}
else if (joystick.position.y > .5) {
target.position = Vector3(transform.position.x,transform.position.y,transform.position.z + 2);
Debug.Log("moveup");
}
else if (joystick.position.y < -.5) {
target.position = Vector3(transform.position.x,transform.position.y ,transform.position.z -2);
Debug.Log("movedown");
}
agent.SetDestination(target.position);
}
Please format your code, if you don't know how, watch the tutorial video on the right.
Also, please refrain from using excessively long question titles. Something more concise will get you many more views on your question, increasing the chance someone will comment or answer.
Answer by Jeff-Kesselman · May 23, 2014 at 08:36 PM
Of course you can only move in one direction. Look at your own code. Its 4 mutually exclusive ifs, one for each direction.
If you want to be able to read more then one at once remove the "else" from the start of each if clause.
as in i wanted the target of my player to be 2 units infront of my player and also at the direction of the joystick, removing the else did help but it still gave me only 4 directions of movement
Answer by abhishek7 · May 24, 2014 at 04:30 PM
All you need to do is remove the else ifs and replace them with just ifs. This way the program will take into account all possible movements in one update and will move as you want. THEN add if x and y is both moved move it so that x is moved up one and y is moved up one to move diagonally; add it for every possibility, enabling diagonal control.
Your answer
![](https://koobas.hobune.stream/wayback/20220613145707im_/https://answers.unity.com/themes/thub/images/avi.jpg)