- Home /
Question by
Madkrumper9 · Sep 30, 2020 at 08:00 PM ·
c#instantiatecannoncannonball
trouble with cannons
I have a cannon that fires with this script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cannon : MonoBehaviour
{
public GameObject barrel;
private int LookVertical;
private int LookHorizontal;
public GameObject cannonBall;
public Transform spawn;
public int thrust;
public float degrees;
public Rigidbody CannonBallRb;
void Start()
{
}
// Update is called once per frame
void Update()
{
degrees = barrel.transform.rotation.x;
if (CheckingForInteractions.HighlightCannon == true)
{
barrel.GetComponent<Renderer>().material.color = Color.red;
}
else if (CheckingForInteractions.HighlightCannon == false)
{
barrel.GetComponent<Renderer>().material.color = Color.blue;
}
if (CheckingForInteractions.UsingCannons == true)
{
Debug.Log("cannons");
barrel.transform.Rotate(LookHorizontal, 0, 0);
if (Input.GetKey(KeyCode.UpArrow) && barrel.transform.rotation.x < 0.95)
{
LookHorizontal = 20;
}
else if (Input.GetKey(KeyCode.DownArrow) && barrel.transform.rotation.x > 0.75)
{
LookHorizontal = -20;
}
else
{
LookHorizontal = 0;
}
if (Input.GetKeyDown(KeyCode.Space))
{
FireCannon();
}
}
void FireCannon()
{
spawn.rotation = barrel.transform.rotation;
GameObject clone = Instantiate(cannonBall, spawn.position, spawn.rotation) as GameObject;
CannonBallRb = clone.GetComponent<Rigidbody>();
CannonBallRb.AddForce(-transform.forward * thrust * 500);
}
the problem is that my cannon doesn't fire at a vertical angle. The horizontal angle, spawn point, and power all work fine i just can't get it to fire upwards at all.
Comment
Is this Script attached to the Barrel Object? transform.forward is the forward of the Transformcomponent your script is attached to. So it would be CannonBallRb.AddForce(- barrel.transform.forward * thrust * 500);
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Classes, MonoBehaviours C# 2 Answers
Instatiante as a child problem 1 Answer