Limiting angle of rigidbody.addforce

Hi,

I’m very new to this so please excuse me. I am trying to put together a 2D Platformer and I have set it so that the player will aim towards the mouse, and rotate the arm sprite so that it looks like he is aiming. But I want to limit the angle of the y axis that they can shoot to + or - 45 degrees. I have managed to limit the rotation of the sprite fine, but the bullet can still fire at any angle and I can’t figure out how to clip it.

Any ideas please?

Many thanks

void FireBullet() {

// Clone bullet
GameObject bulletClone;
bulletClone = Instantiate(bulletPrefab, FiringPoint.position, Quaternion.identity) as GameObject;

// Trajectory Tracking
Vector3 target = Camera.main.WorldToScreenPoint(transform.position);
Vector3 vectorToTarget = (Input.mousePosition - target).normalized;

float fireDirection = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
fireDirection = Mathf.Clamp (fireDirection, -45, 45);

// Fire Bullet
bulletClone.transform.rotation = Quaternion.AngleAxis (fireDirection, Vector3.forward);
bulletClone.rigidbody2D.AddForce (vectorToTarget * bulletSpeed);
print (vectorToTarget);

}

So, you’ve turned the Vector3 into an angle using arctangent, then clamped that angle. Now, you need to turn it back into a vector, using sin and cos:

Vector3 clampedVector = new Vector3(Mathf.Cos(fireDirection * Mathf.Deg2Rad), Mathf.Sin(fireDirection * Mathf.Deg2Rad), 0.0);

Thanks. But dding that line gave me:

error CS1503: Argument ‘#3’ cannot convert ‘double’ expression to type ‘float’

EDIT:

I removed the 0.0 from the end and it works fine now, thank you

Hi,

Using the previous post worked great. But I am having trouble with it when the character is flipped on the x-axis. When rotating the arm sprite I used this:

if (!facingRight && fireDirection > 0)
fireDirection = 180 - fireDirection;
else if (!facingRight && fireDirection < 0)
fireDirection = (fireDirection + 180)*-1;
fireDirection = Mathf.Clamp (fireDirection, -45, 45);

But when the character is flipped and I shoot toward the mouse, using your line, it always shoots to the right

EDIT: Problem solved. Thanks once again