Advertisement
CakeMeister

2D Player Raycast shoot

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