I'm trying to develop a simple shooting mechanism which instantiates a 'shot' based on the angle of rotation of the shooter. My problem here is even though the shooter is oriented at 0*, the shot fires at an angle of 45*(this is what I'm guessing the problem is because when the shooter is oriented at 45*, the shot is fired at exact 90*).
Shooter angle(0,0,0)
Shooter angle(0,0,45)
Note- The ball always launches from the center of the black flattened cylinder object.
Required Code:
public class ShotMoveScript : MonoBehaviour {
public static float xForce;
public Transform shott;
void Update () {
if(Input.GetKey(KeyCode.Q))
{
transform.Rotate(Vector3.forward, 5f);
}
if(Input.GetKey(KeyCode.E))
{
transform.Rotate(Vector3.forward, -5f);
}
if(Input.GetKey(KeyCode.Space))
{
xForce += 0.2f;
}
if(Input.GetKeyUp(KeyCode.Space))
{
Instantiate(shott, transform.position, transform.rotation);
}
}
}
Script attached to the ball which gets instantiated:
public class MovementScript : MonoBehaviour {
void Update () {
Rigidbody2D rb;
rb = GetComponent<Rigidbody2D> ();
rb.gravityScale = 0.8f;
transform.Translate( new Vector3(1,1,0) * ShotMoveScript.xForce * Time.deltaTime, Space.Self);
}
}
You rotate the ball when instantiating it with the third parameter rotation (see reference ). After that you apply a Vector pointing to (1, 1) so the ball will move along that direction relative to his local rotation .
Either pass Quaternion.identity as the third parameter to Instantiate method or move the ball along (1, 0) direction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.