- Home /
My projectile shots wrong with Raycast
I have a problem shooting with Raycast. I am using CineMachine and the shot is tilted, by eye, by the same amount as the camera is tilted. Projectile goes in the correct direction but does not hit exactly where the cursor is. I have no idea why, as I also use the laser with the same settings and everything works fine.
Vector3 mousePos = Mouse.current.position.ReadValue();
mousePos.z = fpsCam.nearClipPlane;
Vector3 worldPosition = fpsCam.ScreenToWorldPoint(mousePos);
Plane plane = new Plane(Vector3.up, 0);
float distance;
Ray ray = fpsCam.ScreenPointToRay(Mouse.current.position.ReadValue());
if (plane.Raycast(ray, out distance)) { worldPosition = ray.GetPoint(distance); }
RaycastHit hit;
Vector3 targetPoint;
// I know this is wrong, but on any other settings it didn't work better.
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.position, out hit, 100, layer)) { targetPoint = hit.point; }
else { targetPoint = ray.GetPoint(100); }
direction = targetPoint - attackPoint.position;
if (Keyboard.current.qKey.wasPressedThisFrame)
{
GameObject gObj = Instantiate(prefab, attackPoint.position, transform.rotation);
gObj.TryGetComponent(out Rigidbody rigid);
rigid.AddForce(direction.normalized * 10f, ForceMode.Impulse);
I tried a dozen or so different changes using variable cameras ViewportToScreenPoint etc., but in the end I can't aim at the ground and the projectile is flying along the terrain or shooting in random directions. Layers are set to Enemy and Ground only. Everything is fine in the scene.
if (Physics.Raycast(ray.origin, ray.direction, out hit, 100, layer)) { targetPoint = hit.point; }
else { targetPoint = ray.GetPoint(100); }
It doesn't change anything unfortunatly. Projectile flies along the terrain, but when I changed layers on Nothing it works like my code with correct layers. When I set layer to check "Enemy", projectile flies above Enemy, but enemy collider isn't bigger than game object.
Your answer
Follow this Question
Related Questions
My Projectile System has Another Bug 1 Answer
Fire Line Renderer from Camera 0 Answers
bullets fly to the wrong direction in specific situations 0 Answers
Raycasr in my fps? 1 Answer
raycast spawn problem 0 Answers