Created
February 20, 2022 04:02
-
-
Save dntf-studio/dc8ec9fb8f7748275abe7c8370b3263a to your computer and use it in GitHub Desktop.
Raycasterを試す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class rayCaster : MonoBehaviour | |
{ | |
[SerializeField, Range(5, 30)] | |
int raySize = 10; | |
public GameObject block; | |
//private int count = 0; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
} | |
// Update is called once per frame | |
void FixedUpdate() | |
{ | |
} | |
private void Update() | |
{ | |
if (Input.GetMouseButtonDown(0)) | |
{ | |
var obj = getRayObj(); | |
if (obj.Item1 == null) return; | |
Destroy(obj.Item1); | |
} | |
else if (Input.GetMouseButtonDown(1)) | |
{ | |
(GameObject obj, Vector3 v_normal) = getRayObj(); | |
if (obj == null) return; | |
Vector3 pos_obj = obj.transform.localPosition + v_normal; | |
Instantiate(block,pos_obj,Quaternion.identity); | |
} | |
} | |
private (GameObject,Vector3) getRayObj() | |
{ | |
int centerX = Screen.width / 2; | |
int centerY = Screen.height / 2; | |
var pos = new Vector3(centerX, centerY, 0.1f); | |
Ray ray = Camera.main.ScreenPointToRay(pos); | |
var hit = new RaycastHit(); | |
if (Physics.Raycast(ray, out hit, raySize)) | |
{ | |
//RayCast Debug | |
Debug.Log($"{hit.collider.gameObject.name}"); | |
Debug.DrawRay(ray.origin, ray.direction * 10, Color.red, 2, false); | |
return (hit.collider.gameObject,hit.normal); | |
} | |
else | |
{ | |
return (null, hit.normal); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment