- Home /
Rising movement
I'm looking to do a rising movement but I'm unsure how to go about it. The idea is you hold the spacebar to rise, and when you let go it goes back down I linked a video below on how the movement would look https://youtu.be/9DtuA1fq0bo777
Answer by FZ_Applications · Jul 10, 2020 at 05:35 AM
This code should do what you want.
public float upForce = 5, upperLimit = 3, lowerLimit = -3;
private Rigidbody2D _rigidbody2D;
private void Start() {
_rigidbody2D = GetComponent<Rigidbody2D>();
}
private void Update() {
if (transform.position.y < upperLimit) {
if (Input.GetKey(KeyCode.Space)) { //Check if space is being pressed down
_rigidbody2D.velocity = Vector2.up * upForce; //Add up force
}
}
//Reset velocity and position if over limits:
if (transform.position.y > upperLimit || transform.position.y < lowerLimit) {
_rigidbody2D.velocity = new Vector2(_rigidbody2D.velocity.x, 0);
transform.position = new Vector2(transform.position.x, Mathf.Clamp(transform.position.y, lowerLimit, upperLimit));
}
}
Hey, firstly I want to thank you for submitting an answer
Unfortunately, I didn't seem to work the way I hoped, the resulting outcome was even if I held the spacebar, the force would only be added for a split second, rather than raising continuously until I let go. I hope you can continue to help
Ok, I've now edited to code to match your usecase.
Answer by MarioSuitedUp · Jul 23, 2020 at 12:55 AM
I'm glad to report that the new code worked! I am grateful for your contribution, so I'd like to commission you to continue helping me as a consultant. If you would be interested in that, you can contact me at my email miguel.mj2021@gmail.com
If not I understand but I would at least like to credit your help when the project is finished.