Search Unity

Knock back for a small pulse with Friction

Discussion in '2D' started by krupps, Dec 13, 2018.

  1. krupps

    krupps

    Joined:
    Oct 17, 2017
    Posts:
    159
    I have a Tilemap with 2 sprites; player and monster. I have a sword which is thrown. When hitting this monster I want to knock him back 2 feet. This is a roguelike game, so no gravity(Rigid Gravity to 0) and overhead.

    I created the Monster object as a GameObject, with a child Sprite object that has the BoxCollider2d, RigidBody2d, SpriteRenderer ( Mass of 20f ). The Sword(Projectile) is the same construct.

    When the sword hits the Monster, I call AddForce on the Sprite Child object. AddForce(0f,3f) to move him 3 feet.

    He moves slowly and never stops. I also tried adding a friction ( Physicis2D with 40 friction ) and doesn't work. Only stops when it slides into a wall.

    Am I creating my Monster Wrong or should I really put the RigidBody2D on the parent GameObject. I used the demo on Ray Wanderlich TileMap demo. Assuming a parent GameObject in case I have multiple sprites with Individual Colliders.

    Any thoughts and what is wrong?
     
  2. Thimble2600

    Thimble2600

    Joined:
    Nov 27, 2015
    Posts:
    165
    You could always try something like this
    currentPosition = Vector2.MoveTowards(currentPosition, destination, speed * Time.deltaTime);

    It moves an object to the given destination over a period of time. It'll need to be worked into the update method somehow. Good destination to set when moving in straight lines is Vector2.Up/Down/Left/Right * distance.

    https://docs.unity3d.com/ScriptReference/Vector2.MoveTowards.html
     
    krupps likes this.
  3. krupps

    krupps

    Joined:
    Oct 17, 2017
    Posts:
    159
    Thanks for the reply! Doing AddForce(0f, 30f, Impulse) and added a Friction value of 80f on the Monster. This causes it to bounce back nice. I wanted the physics to handle it, so I'm not doing it myself. I should probably, change my 0,30 to a direction of the Projectile so it knocks it the correct way.