why is my player sticking to mathf.clamp?
Hello, I added to my player jump script a line of code which uses mathf.clamp so that my player does not leave the screen. It works very well ... But my player remains sticking above or below the screen when it touches this limit and I would just like my player to be blocked and not stick. Can you help me? Below you will find my script so you can see my problem.
void Update () {
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -2.6f, 2.6f), Mathf.Clamp(transform.position.y, -4.8f, 4.8f), transform.position.z);
if (Input.GetKeyDown(UnityEngine.KeyCode.Space) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
this.GetComponent<Rigidbody2D>().AddForce(ForceSaut);
audioSource.PlayOneShot(JumpSound);
}
}
Answer by TRAUHR · Mar 09, 2020 at 05:40 PM
here is the final code that works perfectly!
public Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
if (rb.position.y < -4.8f)
{
rb.position = new Vector2 (0f, -4.8f);
rb.velocity = new Vector2(0,0);
}
else if(rb.position.y > 4.8f)
{
rb.position = new Vector2(0f, 4.8f);
rb.velocity = new Vector2(0,0) ;
}
if (Input.GetKeyDown(UnityEngine.KeyCode.Space) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
rb.AddForce(ForceSaut);
}
}
Answer by streeetwalker · Mar 08, 2020 at 05:12 PM
Hi TrauhrGames ,
the force is still being added through the rigidbody and you are mixing the physics system with direct manipulation of the transform. Try clamping the rigidbody position instead.
file:///Applications/Unity/Hub/Editor/2019.2.11f1/Unity.app/Contents/Documentation/en/ScriptReference/Rigidbody-position.html
@streetwalker thank you for your answer... But how should i do to clamp the rigidbody position?
probably best to create a shortcut "cache" variable to the rigidbody component in the Start method because you are accessing it multiple times:
private RigidBody rb;
void Start() {
rb = GetComponent<Rigidbody2D>();
}
// then use rb in your update function
// then use rb.position.x where you do the clamp
// ins$$anonymous$$d of transform.position.x
//
// same for addforce rb.addForce ...
does that help?
here I changed my script as you advised me, well I think ... because the problem is still present.
public Rigidbody2D rb;
void Start()
{
audioSource = GetComponent<AudioSource>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
transform.position = new Vector3($$anonymous$$athf.Clamp(rb.position.x, -2.6f, 2.6f), $$anonymous$$athf.Clamp(rb.position.y, -4.8f, 4.8f), transform.position.z);
if (Input.Get$$anonymous$$eyDown(UnityEngine.$$anonymous$$eyCode.Space) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
rb.AddForce(ForceSaut);
audioSource.PlayOneShot(JumpSound);
}
}