- Home /
Can anybody tell me what is wrong in this script ?
This program is supposed to move my character forward when there is a positive offset in the Y direction of the joystick and stop moveing when the joystick isn't moving.But my code seems to do that only for the first time.The second time onward, it seems to stop moving when i press the button and moves when i release it.A little help,please.
using UnityEngine;
using System.Collections;
public class move : MonoBehaviour {
public Transform obj;
float threshold = 0.0f;
Vector3 current_pos;
void Start () {
current_pos = obj.position;
Vector3 offset = obj.position - current_pos;
if(offset.y > threshold)
{
transform.Translate(Vector3.forward *10* Time.deltaTime);
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}
public void Update() {
Vector3 offset = obj.position - current_pos;
if(offset.y > threshold) {
transform.Translate(Vector3.forward *10* Time.deltaTime);
transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
if (offset.y <= threshold){
transform.Translate(-Vector3.forward *0* Time.deltaTime);
transform.Translate(Vector3.up *0* Time.deltaTime, Space.World);
}
}
}
Since you set offset = obj.position - current_pos, offset will always equal 0, as you have set to 0 in Start() when you did:
current_pos = obj.position;
Vector3 offset = obj.position - current_pos;
I mean since current_pos = obj.position, even though offset is local in both Start and Update, current_pos will always equal obj.position.
Also you your code doesn't check the joystick position anywhere. To do that you have to use the Input class, e.g. Input.GetAxis:
Your answer
Follow this Question
Related Questions
How to detect which how many of a type a variable a script has 1 Answer
Turning Post-Processing on/off with a key. 0 Answers
How to follow a target (prefab) with the visual scripting: Behavior machine Pro? 0 Answers
Referencing a Cs Script from a JS within the Compile Order 0 Answers
Modal Panel Problem 1 Answer