- usingSystem.Collections;
- publicclass Gun2 : MonoBehaviour {
- publicfloat fireRate =0;
- public LayerMask whatToHit;
- public Transform BulletPrefab;
- float timeToFire =0;
- // Use this for initialization
- spawn = transform.FindChild('spawn');
- Debug.LogError('No Spawn');
- }
- // Update is called once per frame
- if(fireRate 0){
- Shoot ();
- }else{
- if(Input.GetButtonDown('Shoot')&& Time.time> timeToFire){
- Shoot ();
- }
- }
- void Shoot (){
- //gets the position of the mouse
- PosOfMouse = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, Input.mousePosition.z- Camera.main.transform.position.z));
- Vector2 spawnPosition =new Vector2 (spawn.position.x, spawn.position.y);
- RaycastHit2D hit = Physics2D.Raycast(spawnPosition,PosOfMouse - spawnPosition);
- //Effect ();
- //Instantiate (BulletPrefab, spawn.position, spawn.rotation) ; //creates the actual bullet
- Transform BulletInstance = Instantiate (BulletPrefab, spawn.position, spawn.rotation)as Transform;
- Transform MuzzleFlashInstance = Instantiate (MuzzleFlashPrefab, spawn.position, spawn.rotation)as Transform;//Using a Cast, instantiate inside transform variable
- MuzzleFlashInstance.parent= spawn;//sets Instance of Muzzle flash to be a child of the spawn of the bullet.
- float MuzzleFlashSize = Random.Range(0.4f, 0.9f);//Sets the MuzzleFlash to a random size.
- MuzzleFlashInstance.localScale=new Vector3 (MuzzleFlashSize, 0.14f, 0);
- Destroy (MuzzleFlashInstance.gameObject, 0.02f);//Destroys the instance of the MuzzleFlashPrefab after use. .gameObject is used to destroy the transform of an object.
- Debug.DrawLine(spawnPosition, (PosOfMouse -spawnPosition)*100,Color.yellow);
- //when something is actually hit
- Debug.Log('Hit '+ hit.collider.name+' and did '+ Damage +' Damage');
- }
RaycastHit2D itself is a structure and not a class so hit can't be null; this means you have to check for the collider of a RaycastHit2D variable. PDF - Download unity3d for free. RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector2.zero); if (hit.collider!= null). How to make from RayCastHit2D grappling gun / hook in 3 steps? Unity Engine tutorial under 1 minute. Code - https://gist.github.com/FilipCizek/e79f9e0ed07fc. So basically the raycast is for an enemy to check if there is a cliff in front of it. The enemy is knocked back into the air and because of that, the raycast doesn't work properly, so I want to disable it.
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector3.back); then the if (hit.collider!= null) block is always true, even if I click on empty space, and it always returns the same coordinate. To illustrate this, here is a video of me clicking the game view. Mac os x for dvd.