Search Unity

Kick a Ball - Add Force?

Discussion in 'Physics' started by Der_Kevin, Jan 4, 2016.

  1. Der_Kevin

    Der_Kevin

    Joined:
    Jan 2, 2013
    Posts:
    517
    Hey! So I am working on this football game:http://pixelpizza.de/wordpress/?p=297

    and currently i am stuck at the "kick a Ball" part. kicking works great so far and looks like this:


    what i want do do now is, using AddForce/Impulse in a way that the ball is flying into the direction of the kick/where i kick it as soon as the feet collides with the ball or the ball is near enough to the player & the kick button is pressed.

    thanks!
     
    Last edited: Jan 4, 2016
  2. Der_Kevin

    Der_Kevin

    Joined:
    Jan 2, 2013
    Posts:
    517
    so, i tried it a little bit on my own and my current code looks like this:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Dribble : MonoBehaviour {
    5.  
    6.     public float dist = 0;
    7.     public Transform target;
    8.     public Rigidbody rb;
    9.     public float forward; //150000
    10.     public float up;//2000
    11.  
    12.     // Use this for initialization
    13.     void Start () {
    14.         rb = GetComponent<Rigidbody>();
    15.    
    16.     }
    17.    
    18.     // Update is called once per frame
    19.     void Update () {
    20.         dist = Vector3.Distance(target.position, transform.position);
    21.         if (dist  < 0.9f)
    22.         {
    23.             rb.AddForce((target.transform.position - transform.position).normalized * forward * Time.smoothDeltaTime);
    24.         }
    25.  
    26.         if (Input.GetKey(KeyCode.E) && dist  < 2.0f)
    27.         {
    28.             rb.AddForce(Vector3.up * up);
    29.             rb.AddForce((transform.position + target.transform.position).normalized * forward * 0.02f);
    30.         }
    31.    
    32.     }
    33. }
    34.  
    the code is placed on the ball, "public Transform target;" is a invisible gameobject infront of the player
    in theorie it looks pretty good.



    but there are some problems.
    1. the ball is not flying in the right direction. it always moves to the same direction

    2. the ball is "wobbeling" weirdly infront of the player