- Home /
C# Throw GameObject Upon Mouse Click
I'm trying to create a script that throws a gameobject on mouse click. But I'm not sure what code I'm looking for to achieve this. transform.Translate(Vector3.forward * Time.deltaTime); makes the Gameobject move forward continuously without stopping. I want to make it so that the gameobject moves forward very fast and have the gameobject slowly die down till it hits the ground as if you were actually throwing something. Is there other code that modifies a Gameobject's transforms?
Answer by SkaredCreations · May 13, 2014 at 10:00 PM
Is there a reason why you're not using physics to throw it? Adding a rigidbody you could use AddForce on it. Else you could have a float variable as speed by which you multiply Vector3.forward (it will be 0 at start and you set it to 1 or greater upon mouseclick), then use Mathf.Lerp to decrease it down to 0:
Like this for example:
public float throwSpeed = 10;
float speed = 0;
void Update () {
speed = Mathf.Lerp(speed, 0, Time.deltaTime);
transform.Translate(Vector3.forward * speed);
if (Input.GetMouseButtonDown(0))
speed = throwSpeed;
}
RigidBody is definitely the way to go.
As an alternative to addForce you can set an initial velocity for using rigidBody.velocity
I agree with rigidBody, it is also less strain on resources as well in my opinion.
Your answer
Follow this Question
Related Questions
C# Rotate GameObjects Regardless of List Size 2 Answers
C# Change Script Help 1 Answer
C# SetActive GameObject Array 2 Answers
C# GameObject Reverses Z Rotation 0 Answers
C# Find Which Axes Gameobject is on 1 Answer