Advertisement
CakeMeister

2d shooter pistol raycast phan4

Jul 25th, 2017
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class pistol : MonoBehaviour {
  6.     public float shootdelay = 0, damage = 20;
  7.     public LayerMask whattohit;
  8.     public Transform firepoint;
  9.  
  10.     // Use this for initialization
  11.     void Start () {
  12.         firepoint = transform.Find("shootpoint");
  13.     }
  14.    
  15.     // Update is called once per frame
  16.     void Update () {
  17.         shootdelay += Time.deltaTime;
  18.        
  19.         if (shootdelay >= 0.5f)
  20.         {
  21.             if (Input.GetKeyDown(KeyCode.Mouse0))
  22.             {
  23.                 shootdelay = 0;
  24.                 shot();
  25.             }
  26.         }
  27.     }
  28.  
  29.     public void shot()
  30.     {
  31.         Vector2 mousepos = new Vector2
  32.             (Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
  33.              Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
  34.  
  35.         Vector2 firepointpos = new Vector2(firepoint.position.x, firepoint.position.y);
  36.  
  37.         RaycastHit2D hit = Physics2D.Raycast
  38.             (firepointpos, (mousepos - firepointpos), 10f, whattohit);
  39.         Debug.DrawLine(firepointpos, (mousepos - firepointpos) * 100, Color.cyan);
  40.  
  41.         if (hit.collider != null)
  42.         {
  43.             Debug.DrawLine(firepointpos, hit.point, Color.red);
  44.             Debug.Log("We hit " + hit.collider.name);
  45.             hit.collider.SendMessageUpwards("Damage", damage);
  46.         }
  47.            
  48.          
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement