How to control the direction of AddForce based on where I look with my player

I touch the ball, can carry it like dribbling, and unparent it with a press key where I also AddForce it. Theproblem is I cannot control the direction of the ball. I wanna make it go where I look with my player camera like shooting a ball… Tried a couple of ways but couldn’t figure out how to. I also tried “transform.forward”, but this time it chooses random direction I guess based on where it looks with its position and rotation. Here is my script:

using UnityEngine;
using System.Collections;

public class KickingTheBall : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.E))
{
gameObject.GetComponent().AddForce(500, 500, 500, ForceMode.Force);
}

}
}

Try registering your camera as a variable and taking it’s transform as a reference for the force vector.

using UnityEngine;
using System.Collections;

public class KickingTheBall : MonoBehaviour {

public Transform t_Camera; // Drag&Drop your camera over here from the inspector.
private Vector3 v3_Force; // Force reference vector.
public float f_Multiplier; // A multiplier value if the force wouldn't be enough.

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.E))
{
v3_Force = t_Camera.forward;
gameObject.GetComponent<Rigidbody>().AddForce(v3_Force * f_Multiplier, ForceMode.Force);
}

}
}

Though I didn’t test the code, but it shoulda work, if any problem occurs, just let me know so we can look into it again.

Cheers,
Inan

In addition, it’s not a good idea to reach your object’s rigidbody component each time you press E. For optimization purposes, you should register it on the start, and use it whenever you need, so it’d be like :

private Rigidbody rigid_This;

void Start()
{
     rigid_This = GetComponent<Rigidbody>(); // I assume the rigidbody is a component of the gameObject that this code is attached to, so no need to type gameObject.GetComponent, only typing GetComponent is the same as that.
}

And when you press E, only thing you need to do is :

rigid_This.AddForce(.........);

Seems I totally fail at it for now. Guess it’s too much for 1 month of exp to try this stuff :). If I make the ball rigid, when I touch and make it parent it freaks out, and when I don’t make it rig, I cannot add force. and also got a few other problems. So, thanks anyway dude :slight_smile: Iappreciate it.