Hello. I’m trying to build a simple script to limit the motion of an object on a single axis. But I haven’t used unity in ages. And really don’t know what I’m doing. Might be helpful to know if there is a way to expand to restricting motion on multiple axis.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float PlayerSpeed;
public GameObject ProjectilePrefab;
// Update is called once per frame
void Update ()
{
///need to limit motion between 6.5 and -6.5
// Amount to move
float amtToMove = Input.GetAxisRaw("Horizontal") * PlayerSpeed * Time.deltaTime;
// Move player
if Player.transform.position.x < 6.5 Player.transform.position.x > -6.5
transform.Translate(Vector3.right *amtToMove);
if (Input.GetKeyDown("space"))
{
//Fire projectile
Vector3 position = new Vector3(transform.position.x, transform.position.y + (transform.localScale.y / 2));
Instantiate(ProjectilePrefab, position, Quaternion.identity);
}
}
}
You’re looking for Mathf.Clamp
You should be able to clamp the position between two values every frame. Essentially, if the value is greater than the high number/less than the low number, it gets changed to the greater/lesser number, respectively.
Hrrmm… Yeah that’ll work. I’m not sure how to implement this with what I have.
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public float PlayerSpeed;
public GameObject ProjectilePrefab;
function Update ()
{ Player.transform.position.x = Mathf.Clamp(Time.time, 6.5, -6.5);
}
// Update is called once per frame
void Update ()
{
///need to limit motion between 6.5 and -6.5
// Amount to move
float amtToMove = Input.GetAxisRaw("Horizontal") * PlayerSpeed * Time.deltaTime;
// Move player
if (Input.GetKeyDown("space"))
{
//Fire projectile
Vector3 position = new Vector3(transform.position.x, transform.position.y + (transform.localScale.y / 2));
Instantiate(ProjectilePrefab, position, Quaternion.identity);
}
}
}
Also clamp doesn’t seem to work when I put it off on it’s own. It just wants to gravitate towards the higher of the two values.
This is easier if you set transform.position directly rather than using transform.Translate. You can calculate the clamped X position with code like this:-
newX = Mathf.Clamp(transform.position.x + amtToMove, -6.5, 6.5);
Then, set the position:-
transform.position.x = newX;