Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a group of objects that I allow my player to toss around the scene in zero gravity. However I want to create type of invisible bounds after a certain height. So far when the object reaches a certain upward bounds, I have been doing this in my FixedUpdate...

GetComponent<Rigidbody>().velocity = GetComponent<Rigidbody>().velocity - Vector3.Project(GetComponent<Rigidbody>().velocity, transform.up);

...which works in a sense, but because it is using transform.up, it is removing velocity from both upwards and downwards movement, and I need to restrict it to just upwards movement. Is this possible?

question from:https://stackoverflow.com/questions/65847997/how-to-prevent-upward-rigidbody-velocity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

Maybe you can check the y component of the velocity and if it's positive (upwards) set it to 0? If it's negative (downwards) just keep it.

PS. I think you should get a variable referencing the rigidbody component to minimize the GetComponent calls.

Vector3 v = rb.velocity; //get the velocity
v.y = v.y > 0 ? 0 : v.y; //set to 0 if positive
rb.velocity = v; //apply the velocity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...