Hello everyone !
I’m creating a mobile game. It’s a little game with a cannon firing bullets. I used the instantinate function to duplicate the gameobjects (cannonball). It works very well in itself but it is necessary to define a key to allow the cannon to shoot. But here’s the problem: it’s a mobile game and to shoot you have to use the key on the keyboard. I put a UI Button on the canvas for the gun to fire. I put scripts in it, I tried many things, nothing happens …
How can I fire my cannon without using the keys? (button)
Here is the script :
using System.Collections;
using UnityEngine;
public class CannonBallSpawn : MonoBehaviour
{
public Rigidbody CannonBallPrefab;
public Transform barrelEnd;
void Update()
{
if (Input.GetButtonDown ("Shoot"))
{
Rigidbody cannonBallInstance;
cannonBallInstance = Instantiate(CannonBallPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
cannonBallInstance.AddForce(barrelEnd.forward * 4000);
}
}
}
misher
2
First create a separate method for shooting like so:
public void Shoot() {
Rigidbody cannonBallInstance = Instantiate(CannonBallPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
cannonBallInstance.AddForce(barrelEnd.forward * 4000);
}
Then you can activate it in 2 different ways:
-
From a button on canvas, you simply add a listener to the button in the inspector, drag the object with the scrip onto it and select the Shoot method from the dropdown list.
-
From touching the screen, this can be as simple as:
void Update() {
if(Input.GetMouseButtonDown(0)) {
Shoot();
}
}