# How to adjust the shooting angle of an object

I've been trying to add an angle adjustment feature to a power bar that I got from unity3dStudents. But I can't seem to get the code right. I'm using addforce to rigidbody, it works but the power is too great. I also found that rotating the object it's shooting from changes the angle. But I don't know how to proceed from that.

Can somebody show me the problem with the script below, as in how to add height to the addforce without it going to far up or to the side? Or how to change the angle of the object?

var theAngle : int;

var maxAngle : int = 130;
var minAngle : int = 0;

var angleIncreasing : boolean = false;
var angleDecreasing : boolean = false;

var rotationSpeed  : float = 10;
var ball        : Rigidbody;

var spawnPos : Transform;
var shotForce : float = 25;

function Update () {

if(Input.GetKeyDown("k")){
angleIncreasing = true;
angleDecreasing = false;
}
if(Input.GetKeyUp("k")){
angleIncreasing = false;
}
if(Input.GetKeyDown("l")){
angleIncreasing = false;
angleDecreasing = true;
}
if(Input.GetKeyUp("l")){
angleDecreasing = false;
}

-------
if(angleIncreasing){
theAngle += Time.deltaTime * rotationSpeed;
if(theAngle > maxAngle){
theAngle = maxAngle;
}
}
if(angleDecreasing){
theAngle -= Time.deltaTime * rotationSpeed;
if(theAngle < minAngle){
theAngle = minAngle;
}
}

}

function Shoot(power : float, angle : int){
----
var forward     : Vector3 = spawnPos.forward;
var upward  : Vector3 = spawnPos.up;

----
}


This is suspect:

pFab.AddForce(forward * power * shotForce);


This code is equivalent to:

pFab.AddForce(forward * power * shotForce + upward * angle * 10);


Lots of variables going into that force, which is probably the cause of "the power is too great". You're also not linearly increasing or decreasing the actual angle but its sine, this means (if I'm not mistaking) that the way you're using "angle" in your code contributes superlinearly to the actual angle.

Try this:

var angleRad : float = angle / 180.0 * Mathf.PI; // Convert angle to radians.


Now angle represents the actual direction of the force w.r.t. the up and forward vectors, and the size of the force will be equivalent to power * shotForce (as long as upward and forward are unit vectors).

P.S. If you're not doing anything else with angleIncreasing/Decreasing, I would suggest you rewrite your Update to this:

if ( Input.GetKeyDown("k") ) {
theAngle += Time.deltaTime * rotationSpeed;
if ( theAngle > maxAngle ) {
theAngle = maxAngle;
}
}
if ( Input.GetKeyDown("l") ) {
theAngle -= Time.deltaTime * rotationSpeed;
if ( theAngle < minAngle ) {
theAngle = minAngle;
}
}

• would angleRad = a float? – Blue Jun 21 '12 at 14:30
• Good point! Yes, it should be, edited. - It's probably best to make theAngle and angle floats too by the way (and if it suits you use radians instead of degrees everywhere), since Time.deltaTime * rotationSpeed will lose precision when you assign it to theAngle. – Eric Jun 21 '12 at 14:42