Hello, I’m trying to target the opponent with a mouse.
I have this code that should work.
But after the character turns, the shooting is deflected.
If I rotate the characters, the shooting is directed in a different direction from where the cursor lies.
I went through some topics on the Internet, it did not help me.
Can I ask for less help?
Where am I making a mistake?
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Rigidbody clone;
clone = Instantiate(projectile, _weapons.transform.position, _weapons.transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(hit.point - _weapons.transform.position);
Debug.DrawLine(ray.origin, hit.point);
}
transform.TransformDirection translates from local to world space this will be where your issue lies. Just do (hit.point - _weapons.transform.position).normalized;
Sorry for late response never got notified that you responded.
To clarify you want the bullet to fire in a 30 degree cone around the target? So if you fired a few shots they would fire at different angles be still be towards that target?
If thats so you can do something like:
Public float fireRadius = 0.3f;
Vector3 targetPos = hit.point;
//Calculating a random direction
Vector3 variedOffset = new(Random.Range(-1.0f, 1.0f), Random.Range(-1.0f, 1.0f), 0.0f);
variedOffset.normalise();
//Scale it within our radiu
variedOffset *= Random.Range(0.0f, fireRadius);
//Offset the target relative to our rotation
targetPos += _weapons.transform.right * variedOffset.x;
targetPos += _weapons.transform.up * variedOffset.y;
Just use targetPos over hit.point for the rest and it should be good.