Unity プログラミング初心者です。2d版マインクラフトのようなブロックを設置、破壊するゲームを制作しています。
ブロックを置くことができる最大値を設定し設置すると-1、破壊すると+1のようなコードを書いてみたのですが、設置と破壊を繰り返すと設置できる最大値が増えたリ減ったりしてしまいます。( PlaceCountが-1や2のようになる)
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class BuildCtrl : MonoBehaviour { public RuleTile grassTile; public Tilemap groundTilemap; public Vector3Int location; RaycastHit2D hit; float blockDestroyTime = 0.0f; public float reach; public int PlaceCount; public int MaxPlace; Vector3 direction; [SerializeField] bool destroyingBlock = false; [SerializeField] bool placingBlock = false; private void Update() { } private void FixedUpdate() { Vector3 mouse_position = Camera.main.ScreenToWorldPoint(Input.mousePosition); if (Vector2.Distance(transform.position, mouse_position) >= reach) { if (Input.GetMouseButton(0) || Input.GetMouseButton(1)) { RayCastDirection(); } } location = groundTilemap.WorldToCell(mouse_position); Vector3 complementPos = new Vector3(groundTilemap.cellSize.x / 2, groundTilemap.cellSize.y / 2, 0); Vector3 worldPos = groundTilemap.CellToWorld(location) + complementPos; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); int layerMask = 1 << 6; float maxDistance = 10; //ヒット判定にPysics2D.Raycastを使用 RaycastHit2D hit = Physics2D.Raycast((Vector2)ray.origin, (Vector2)ray.direction, maxDistance, layerMask); if (hit.collider) { Debug.Log(hit.collider.gameObject.name); } } void RayCastDirection() { int layerMask = 1 << 6; float maxDistance = 10; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit2D hit = Physics2D.Raycast((Vector2)ray.origin, (Vector2)ray.direction, maxDistance, layerMask); //左クリック時コライダー判定があり、destroyingBlockがfalseなら関数を呼びPlaceCountを-1する if ((Input.GetMouseButton(0))) { if (hit.collider && !destroyingBlock) { destroyingBlock = true; StartCoroutine(DestroyBlock()); PlaceCount--; } } //右クリック時コライダー判定が無しかつ、placingBlockがfalse、PlaceカウントがMaxPlaceより少ない時 関数を呼びPlaceCountを+1する if ((Input.GetMouseButton(1))) { if (!hit.collider && !placingBlock && MaxPlace >= PlaceCount) { placingBlock = true; StartCoroutine(PlaceBlock()); PlaceCount++; } } } IEnumerator DestroyBlock() { yield return new WaitForSeconds(blockDestroyTime); groundTilemap.SetTile(location, null); destroyingBlock = false; } IEnumerator PlaceBlock() { yield return new WaitForSeconds(0.0f); groundTilemap.SetTile(location, grassTile); placingBlock = false; } }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/06/19 07:55
2022/06/19 09:34 編集