Skip to content

Instantly share code, notes, and snippets.

@tubakihimeLoveHate
Created February 13, 2022 23:15
Show Gist options
  • Save tubakihimeLoveHate/1753889f492283d20466b46375c5ec0f to your computer and use it in GitHub Desktop.
Save tubakihimeLoveHate/1753889f492283d20466b46375c5ec0f to your computer and use it in GitHub Desktop.
[クリエイティブ機能作ってみた記事]配置プレビュー付きコード
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CreateRayTarget : MonoBehaviour
{
[SerializeField]
private float distance = 20.0f;
[SerializeField]
private GameObject clone;
private Camera camera;
private GameObject previewClone;
[SerializeField]
private Material previewMaterial;
private void Start()
{
camera = GetComponent<Camera>();
previewClone = Instantiate(clone);
previewClone.GetComponent<MeshRenderer>().material = previewMaterial;
previewClone.GetComponent<BoxCollider>().enabled = false;
}
// Update is called once per frame
void Update()
{
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, distance))
{
Vector3 movement = Vector3.Scale(previewClone.transform.localScale, hit.normal) / 2;
previewClone.transform.position = new Vector3(hit.point.x + movement.x, hit.point.y + movement.y, hit.point.z + movement.z);
if (Input.GetMouseButtonUp(0))
{
Instantiate(clone, previewClone.transform.position, Quaternion.identity);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment