- Home /
Question by
JaredHD · Jan 01, 2018 at 09:27 AM ·
c#grid based gamewallssnapping
Prevent this script from snapping diagonally
The problem
Hello, I have a grid snapping script. The problem is that it sometimes snaps diagonally. The issue is that when placing walls down, the walls than go diagonally.Here is the script. Any ideas on how to prevent the issue?
using UnityEngine;
public class MouseManager : MonoBehaviour
{
public static MouseManager instance;
[Header("Objects to be added in inspector")]
public TerrainCollider terrainCollider;
public GameObject mouseSelector;
[Header("Grid placement space")]
public int gridSize = 5;
private void Awake()
{
instance = this;
}
private void Update()
{
mouseSelector.transform.position = SnapPosition(GetWorldPoint());
}
public Vector3 GetWorldPoint()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (terrainCollider.Raycast(ray, out hit, Mathf.Infinity))
return hit.point;
return Vector3.zero;
}
public Vector3 SnapPosition(Vector3 pos)
{
Vector3 snapped;
snapped.x = Mathf.Floor((pos.x + 0.5f) / gridSize) * gridSize;
snapped.y = Mathf.Floor((pos.y + 0.5f) / gridSize) * gridSize;
snapped.z = Mathf.Floor((pos.z + 0.5f) / gridSize) * gridSize;
return snapped;
}
}
I was thinking about making a list of possible move spaces, and if the mouse moves really far fast, it'll loop over each move snapping to the spot fast, rather than jump to the new snapped position and skip other possible snapped positions.
Any help would be greatly appreciated. ~Jared
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
An OS design issue: File types associated with their appropriate programs 1 Answer
Raycast Snapping Problem. 0 Answers