Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Laser : MonoBehaviour {
- public GameObject prefab;
- public float laserPower;
- // Use this for initialization
- void Start () {
- }
- // Update is called once per frame
- void Update () {
- //we use rays to project invisible lines at a distance
- //in this case, we are using the ScreenPointToRay function of our main camera
- //to convert the mouse position on the screen into a direction projected through the screen
- //(in class, i drew a dinosaur on the other side)
- Ray beam = Camera.main.ScreenPointToRay(Input.mousePosition);
- //draw our debug ray so we can see inside unity
- //the ray starts from beam.origin and is drawn to 1000 units in the rays direction (beam.direction)
- Debug.DrawRay(beam.origin, beam.direction * 1000f, Color.red);
- //declare and initialize our raycasthit to store hit information
- RaycastHit beamHit = new RaycastHit();
- //this both casts the ray "beam" and returns true if the ray hits any collider
- //the second parameter is where our raycasthit information is stored
- //the third parameter is how far to cast the ray
- if (Physics.Raycast(beam, out beamHit, 1000f)){
- //if the raycast hits a rigidbody and the player is pressing the right mouse button
- if (beamHit.rigidbody && Input.GetMouseButton(0)){
- //we use insideunitsphere to get a random 3D direction and multiply the direction by our power variable
- beamHit.rigidbody.AddForce(Random.insideUnitSphere * laserPower);
- }
- //if the raycast hits something and the player is pressing the right mouse button
- if (Input.GetMouseButton(1)){
- //Instantiate(prefab, beamHit.point, Quaternion.identity);
- //Debug.Log(beamHit.point);
- }
- //if the raycast hits something and the player is pressing the middle mouse button
- if (Input.GetMouseButton(2)){
- //Destroy this will delete this script from the object its attached to
- //Destroy(this);
- //we can also destroy a given gameobject
- //using our raycasthit beamhit to access the transform of the thing hit and its parent gameobject
- //Destroy(beamHit.transform.gameObject);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement