Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Player GameObject pushes objects around gently instead of HITTING them (mouse input)

Discussion in 'Physics' started by Shin_Toasty, Sep 25, 2017.

  1. Shin_Toasty

    Shin_Toasty

    Joined:
    Jun 15, 2017
    Posts:
    48
    I am new to Unity and I'm asking this question because I can't find an answer anywhere.

    I'm moving my GameObject with mouse (it's a spaceship in zero gravity) but when it hits any object, regardless of how fast you move the mouse, it just pushes it neatly around instead of sending it flying in the opposite direction.

    I'm using the following to make it dive into another ship and ram it:

    Code (CSharp):
    1.         float moveShip = Input.GetAxis("Mouse Y");
    2.         float step = diveSpeed * moveShip * Time.deltaTime;
    3.         transform.position = Vector3.MoveTowards (transform.position, target.position, step);
    What do I need to add? When other objects hit each other, all is fine, no pushing. They aren't controlled by the mouse though.

    No errors in my console BTW.
     
  2. Mitnainartinarian

    Mitnainartinarian

    Joined:
    Jun 3, 2017
    Posts:
    16
    In order to get the physics system working properly, you typically go through operations on the Rigidbody rather than on the Transform. Try replacing transform.position = ... with Rigidbody.MovePosition if your Rigidbody is kinematic.You can also use Rigidbody.AddForce.

    Since you're new, if you need the Rigidbody, do GetComponent<Rigidbody>(), then call MovePosition or AddForce on the returned object (it would be best to call GetComponent once and store the returned value, for performance reasons).
     
    Shin_Toasty likes this.
  3. Shin_Toasty

    Shin_Toasty

    Joined:
    Jun 15, 2017
    Posts:
    48
    Thanks Mitnainartinarian, I thought transform would take the Rigidbody with it. Also thought there might be some special code I needed here because I'm using mouse input.

    This works:

    Code (CSharp):
    1.         float diveShip = Input.GetAxis("Mouse Y") /  5;
    2.         Vector3 direction =  (target.transform.position - transform.position).normalized;
    3.         ship.MovePosition (transform.position + direction * diveShip);
    The rb is ship and the / 5 is just there to slow it down. No errors in console, but if you see anything wrong pls let me know.

    I hope I get quick answers every time I beg here!
     
  4. Plystire

    Plystire

    Joined:
    Oct 30, 2016
    Posts:
    142
    Changes to the transform will bring the rigidbody along for the ride, but in a completely different manner. It's more akin to teleportation than simple movement. ;)
     
    Shin_Toasty likes this.