- Home /
Shoot cannonballs at the push of a button
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);
}
}
}
Answer by misher · Feb 11, 2019 at 11:39 AM
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(); } }
It works ! Thanks a lot :)
If you want i put your nick in the credits of my game when its finished
Haha, I'm glad my answer was helpful to you, which method you've ended up using: click on screen or button?
I've used the button method because the click on the screen is already used for aim :(
Your answer
Follow this Question
Related Questions
For mobile games, how could you divide the screen into three buttons vertically? 1 Answer
Making one directional virtual joystick OR smoothly transitioning between buttons 0 Answers
How do I make a "move pad" on the screen? (Mobile) 1 Answer
is possible press 2 buttons at the same time Mobile touch? 0 Answers
How do I detect touch on another object and check by tag/name? 1 Answer