- Home /
How to aim a ball with cross hair?
I am making a game and the player can pick up and throw a ball. The problem is that the script that I use adds force to where the camera is looking and the aiming is inaccurate. I'm trying the make it so that the player can throw the ball exactly to where the cross hair is pointing.
Here is my script using UnityEngine; using System.Collections;
public class throwx : MonoBehaviour {
public Rigidbody rb;
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.
public GameObject carryact;
public Transform ball;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (Time.deltaTime == 0f)
return;
if(carryact.activeInHierarchy)
{
if (Input.GetMouseButtonDown(0))
{
v3_Force = t_Camera.forward;
ball.GetComponent<Rigidbody>().AddForce(v3_Force * f_Multiplier, ForceMode.Force);
}
}
}
}
so, is the crosshair going to be in the center of the screen, or do you want the crosshair to be where the object is going to land. Why not just turn off gravity on the rigidbody? I'm confused.
Sorry for the confusion. It's a third person and yes the cross hair will be in the center of the screen with the player to the left. I also have another script the exact same as this but for the y axis. I am trying to make the ball go straight and stay in the air longer but eventually come to the ground so that the player can pick it up again. I also want it to go straight where the cross hair is pointing.
Answer by badadam · Jan 13, 2019 at 05:55 PM
Add UI Image and make your cross hair sprite UI Image's Source Sprite
Render Mode of The Canvas which is parent of Image object must be World Space.
The pivot of Image must be 0.5 for x and y. Make the canvas which is parent of image child of aiming object. Use positions and scale values of Rect tranform for position to screen. And use this codes
public RectTransform crossHair;
public Transform ball;
public float f_Multiplier;
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
ball.position = crossHair.position;
Vector3 forceV3 = crossHair.forward;
ball.GetComponent<Rigidbody>().AddForce(forceV3 * f_Multiplier, ForceMode.Force);
}
}
Answer by sh_code · Jan 13, 2019 at 08:45 PM
you are adding force, therefore using physics. ball has a weight and is affected by gravity. therefore it's going to fall downwards, in addition to flying forward. therefore, it will NEVER fly in straight line, meaning it will NEVER land where your crosshair is pointing.
either you need to account for this in the direction of the force you're adding (objects fly in an arc, so make them fly in arc which ends at the crosshair position), or make the ball not be affected by gravity, or ditch the physics system alltogether and just make the ball move in a straight line.