- Home /
Help: Shooting a cube
Would someone be kind enough of making a script that fires a cube from the player when the mouse is clicked? I can't find anything online on how to do that. Thanks!
Answer by robertbu · Jan 21, 2013 at 10:23 PM
Here is a short C# script that shoots blocks from the camera at the point you click on the screen. Attach this script to any game object in the scene, and click away.
using UnityEngine;
using System.Collections;
public class FireCube : MonoBehaviour {
void Update () {
if (Input.GetMouseButtonDown (0))
{
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
go.transform.position = Camera.main.transform.position;
Rigidbody rb = go.AddComponent<Rigidbody>();
Vector3 v3T = Input.mousePosition;
v3T.z = 10.0f;
go.transform.LookAt (Camera.main.ScreenToWorldPoint(v3T));
rb.AddRelativeForce(Vector3.forward*1000);
}
}
}
There are some stuff in these few lines that may be more intermediate than beginner code. Plus there are problems not solved (like the block are never destoryed). If you struggle with this code you might want start by figuring out out to attach a Rigidbody component to a cube in the editor and then move it in a script with AddForce().
Your answer
Follow this Question
Related Questions
Make a rolling ball always on ground without falling when reaching the edges of the map 1 Answer
Force is changing shape? 0 Answers
Physical shots 3 Answers
Freezing movement on Z axis. 1 Answer