- Home /
Other
Mathf.Clamp with the rigidbody
Hi guys, in this script if you press Q the object goes up, instead if you press E, it goes down. but it should have limits for both (max hight and minimum down position). I sow that I have to use Mathf.Clamp to set the limits, but in the unity API ther's an example with "transform.position", I don't have It in my script. Where Can I put The Mathf.Clamp limits in my script? Thank you and happy holidays to everyone :)
#pragma strict
var GoUp = 1.0;
var GoDown = 5.0;
function FixedUpdate() {
if (Input.GetKey(KeyCode.Q)) {
GetComponent.<Rigidbody>().AddForce(transform.up * GoUp);
}
else if (Input.GetKey(KeyCode.E)) {
GetComponent.<Rigidbody>().AddForce(-transform.up * GoDown);
}
else if (Input.GetKey(KeyCode.W)) {
GetComponent.<Rigidbody>().velocity = GetComponent.<Rigidbody>().velocity * 0.9;
}
}
this is the code that I use for that
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : $$anonymous$$onoBehaviour { public float speed = 10f;
private float _limiteH = 8f;
private float _limiteV = 4f;
private Vector2 _moveH;
private Vector2 _moveV;
private Rigidbody2D _rb;
void Awake()
{
_rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
_moveH= new Vector2(horizontalInput,0f);
_moveV = new Vector2(0f,verticalInput);
}
void FixedUpdate()
{
float horizontalVelocity = _moveH.normalized.x * speed;
if((_rb.position.x >= _limiteH && horizontalVelocity == speed)|| _rb.position.x <= -_limiteH && horizontalVelocity == -speed)
{
_rb.velocity = new Vector2(0,_rb.velocity.y);
}
else
{
_rb.velocity = new Vector2(horizontalVelocity, _rb.velocity.y);
}
float verticalVelocity = _moveV.normalized.y * speed;
if((_rb.position.y >= _limiteV && verticalVelocity == speed)|| _rb.position.y <= -_limiteV && verticalVelocity == -speed)
{
_rb.velocity = new Vector2(_rb.velocity.x,0);
}
else
{
_rb.velocity = new Vector2(_rb.velocity.x, verticalVelocity);
}
}
}
Answer by JimNero_009 · Dec 26, 2015 at 03:46 PM
The clamp function restricts the value of something to be between two values. In your case, you need to restrict your y position, so you need to firstly define two floats (ymin, ymax) and add a check in your code that your rigidbody's y position is within this range. You could do this without a clamp function - have an if statement that checks the rigidbody's y position, and if it is outside of this range, set the velocity in either the up or down direction to be zero. Otherwise, just before you end your FixedUpdate function I think adding a line a bit like this;
transform.position.y = new Vector3(Mathf.Clamp(transform.position.y, ymin, ymax), 0, 0);
might do the trick, but have not tested it.