I'm implementing my first Third person game. In this game I want to shoot at the direction of the mouse. Therefore I cast a ray from the camera to the ground. To make the shooting better I draw a line from the player to the current mouse position (see screenshot).
If the player presses the fire button, a bullet should spawn and shoot in the direction of the line renderer.
Unfortunally the bullet is not flying to the direction of the mouse and I'm not sure why?
Both scripts: Line renderer and bullet spawn and shoot are on the same gameobject.
Current Code
Line Renderer:
void Update()
{
Vector3 pos = new Vector3(200, 200, 0);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
linePointing = new Vector3(hit.point.x, hit.point.y, hit.point.z); // really unnecessary but I want the line Pointing as my hit point
linePointing.y = gameObject.transform.position.y;
Vector3 localCord = gameObject.transform.InverseTransformPoint(linePointing);
float angle = Mathf.Atan(localCord.x / localCord.z) * Mathf.Rad2Deg;
//This is just so the player cant shoot in every direction
if (Mathf.Abs(angle) < 80 && localCord.z > 0)
{
m_lineRenderer.SetPosition(1, localCord);
m_lineRenderer.SetPosition(2, localCord * 100);
}
}
}
Bullet spawn (also in update)
GameObject bullet = Instantiate(bulletPrefab);
bullet.transform.parent = gameObject.transform.parent;
Physics.IgnoreCollision(bullet.GetComponent<Collider>(), bulletSpawn.parent.GetComponent<Collider>());
bullet.transform.position = bulletSpawn.position;
Vector3 rotation = bullet.transform.rotation.eulerAngles;
bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);
bullet.GetComponent<Rigidbody>().AddForce(getShootingDirection().normalized * bulletSpeed, ForceMode.Impulse);
//Change parent, so the player movement doesnt affect the bullet
bullet.transform.parent = null;
Get shooting direction-Method This method is same as the line renderer ones but I want to have it separate
private Vector3 getShootingDirection()
{
Vector3 linePointing = Vector3.zero;
Vector3 localCord = Vector3.zero;
Vector3 pos = new Vector3(200, 200, 0);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
linePointing = new Vector3(hit.point.x, hit.point.y, hit.point.z)
{
y = hit.point.y + 0.5f
};
localCord = gameObject.transform.InverseTransformPoint(linePointing);
}
return localCord;
}
Picture of line renderer:
RigidbodyAddforce adds a force in world coordinates, and I think you are adding the force in local coordinates. You can check that out.