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

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

unity3d - How to prevent upward rigidbody velocity?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...