Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Throw an object using physics? (Unity)

So, I have been working for 4+ hours now, and I am trying to make an object that the player can throw. I was thinking of like tossing it, (not throwing it far, like .5 meters,) and I can’t seem to get it. I have tried adding force through rigidbody, making an animation, and just changing its transform. Can anyone help me if has anyone had to do something similar, if so how did you do it?

I don’t have any code examples, because nothing worked. (Please don’t just say Rigidbody, can you give examples. Thanks.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I am still unable to add comments due to reputation, so here is a generic approach to setting up a rigidbody to be thrown based on mouse input.

 Camera cam;
 Rigidbody r;
 Vector3 direction = cam.ScreenPointToRay(Input.mousePosition);
 r.AddForce(direction * 100);

The code is using the camera of your scene, the rigidbody of the object you want to throw, it then converts the screen space of the mouse input to a raycast to get a direction to throw the object, then adds a force on that object in that direction.

If you code looks something like this, there is a good chance you are changing the velocity or transform of the object elsewhere. It could also be colliding with another object and be getting stopped.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...