Skip to content

Instantly share code, notes, and snippets.

@JackKell
Created May 4, 2019 19:52
Show Gist options
  • Save JackKell/a8b899d4e9ff76d2044ad1258b4bfce1 to your computer and use it in GitHub Desktop.
Save JackKell/a8b899d4e9ff76d2044ad1258b4bfce1 to your computer and use it in GitHub Desktop.
An Example of raycasting in unity
using System.Collections.Generic;
using UnityEngine;
public class Cloud : MonoBehaviour
{
[SerializeField] private float _speed;
[SerializeField] private int _rays;
[SerializeField] private float _distance;
[SerializeField] private float _force;
private Vector2 _moveInput;
private Rigidbody2D _rigidbody;
private BoxCollider2D _boxCollider2D;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody2D>();
_boxCollider2D = GetComponent<BoxCollider2D>();
}
private void Update()
{
HandleSneeze();
}
private void HandleSneeze()
{
if (!Input.GetKeyDown(KeyCode.Space)) return;
Vector3 startPosition = transform.position;
startPosition += new Vector3(-_boxCollider2D.bounds.extents.x, _boxCollider2D.bounds.extents.y);
float xOffset = _boxCollider2D.bounds.size.x / (_rays - 1);
HashSet<Rigidbody2D> rigidbodies = new HashSet<Rigidbody2D>();
for (int i = 0; i < _rays; i++)
{
Vector3 offset = new Vector3(i * xOffset, 0, 0);
Vector3 origin = startPosition + offset;
RaycastHit2D hitInfo = Physics2D.Raycast(origin, Vector2.up, _distance);
if (!hitInfo.rigidbody) continue;
rigidbodies.Add(hitInfo.rigidbody);
Debug.DrawLine(origin, hitInfo.point, Color.black, 0.3f);
Debug.Log(hitInfo.rigidbody.name);
}
foreach (Rigidbody2D body in rigidbodies)
{
Debug.Log($"Adding for to {body.name}");
body.AddForce(Vector2.up * _force, ForceMode2D.Impulse);
}
}
private void FixedUpdate()
{
_rigidbody.velocity = new Vector3(Input.GetAxisRaw("Horizontal") * _speed, 0, 0);
}
private void OnDrawGizmosSelected()
{
_boxCollider2D = GetComponent<BoxCollider2D>();
Vector3 startPosition = transform.position;
startPosition += new Vector3(-_boxCollider2D.bounds.extents.x, _boxCollider2D.bounds.extents.y);
// float xOffset = _boxCollider2D.bounds.size.x / (_rays - 1);
// for (int i = 0; i < _rays; i++)
// {
// Vector3 offset = new Vector3(i * xOffset, 0, 0);
// Vector3 origin = startPosition + offset;
// Gizmos.DrawLine(origin, origin + Vector3.up * _distance);
// }
Vector3 center = new Vector3(transform.position.x, startPosition.y + _distance / 2, 0);
Vector3 size = new Vector3(_boxCollider2D.size.x, _distance);
Gizmos.DrawWireCube(center, size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment