Search Unity

Add force in the direction that raycast gets hit

Discussion in 'Physics' started by amirivala, Sep 16, 2015.

  1. amirivala

    amirivala

    Joined:
    May 29, 2013
    Posts:
    57
    Hi, im trying to make a fighting game, and i have two questuion.
    So for the punch I'm using raycasting to determine if its hit something and here is the code:
    Code (CSharp):
    1.     void Shoot ()
    2.     {
    3.            
    4.         shootRay.origin = rightHand.transform.position;
    5.         shootRay.direction = transform.forward;
    6.        
    7.         if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
    8.         {
    9.             Debug.DrawLine(rightHand.transform.position, shootHit.transform.position, Color.red,2.0f);
    10.  
    11.             Rigidbody enemyrigid = shootHit.collider.GetComponent <Rigidbody> ();
    12.  
    13.  
    14.             // If the EnemyHealth component exist...
    15.             if(enemyrigid != null)
    16.             {
    17.  
    18.  
    19.                 //enemyrigid.AddForce(shootRay.origin + shootRay.direction * punchPower ,ForceMode.VelocityChange);  // Not sure if i should use AddForce Or Velocity
    20.                 enemyrigid.velocity = (shootHit.point - rightHand.transform.position).normalized * punchPower;
    21.  
    22.                
    23.             }
    24.            
    25.         }
    26.  
    27.         else
    28.         {
    29.             Debug.Log(“Didn’t Hit Anything”);
    30.            
    31.         }
    32.     }


    So my question is:
    1. My main question is when i hit Fire Button it shoots ray from like right hand to Shootable thing so im gonna add force in the direction that Raycast draw, is there anyway so i can do it ? you can see the image example

    http://i.imgur.com/0O3MNrV.jpg?1

    2. Should i use AddForce or Velocity to move the enemie backward? is there any diffrence? because i tried both of them and both works the same!
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    What do you use for raycasting? Every raycast has a direction variable. You can just use AddForce with that direction in it. You could also set the forcemode to velocitychange, so its "instant".