Wondered if any one can help. I have limited the movement on the x axis but cannot on the z axis. I have tried to have a go myself ( as you can see ) but I’m having trouble now. Can anyone help.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
//properties go here
public float Speed = 10f; // speed of player
// Update is called once per frame
void Update () {
//custom functions go here
//move the player
//calculate the amount of movement
float LeftRightMovement = Input.GetAxis(“Horizontal”) * Speed * Time.deltaTime;
float UpDownMovement = Input.GetAxis(“Vertical”) * Speed * Time.deltaTime;
//make the movement happen
transform.Translate(LeftRightMovement,0,0);
transform.Translate(0,0,UpDownMovement);
//Restrict movement between two values
if (transform.position.x <= -9f || transform.position.x >= 9f)
(transform.position.z <= -9f || transform.position.z >= 9f)
}
float zPos = Mathf.Clamp(transform.position.z,-9f, 9f);
float xPos = Mathf.Clamp(transform.position.x,-9f, 9f);
//Clamp between min -9 and max 9
transform.position = new Vector3(xPos, transform.position.y,zPos);
}
}
}
I think you went a little far. You are translating it up and down, then checking the positions and stuff. Then you are clamping things.
Why not just get the position, add the amoutn you want to add, clamp it, then set it. No Translations.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
//properties go here
public float Speed = 10f; // speed of player
// Update is called once per frame
void Update () {
//custom functions go here
//move the player
//calculate the amount of movement
float LeftRightMovement = Input.GetAxis("Horizontal") * Speed * Time.deltaTime;
float UpDownMovement = Input.GetAxis("Vertical") * Speed * Time.deltaTime;
Vector3 pos = transform.position;
pos += new Vector3(LeftRightMovement, 0, UpDownMovement);
pos.x = Mathf.Clamp(pos.x, -9, 9);
pos.z = Mathf.Clamp(pos.z, -9, 9);
transform.position = pos;
}
}
Thanks BigmisterB. I’m Still finding it hard with scripting. But any ways thanks you again :).
I’m just learning as I go. I’m watching someone online do it but there scripting in java and I’m trying to translate !