Untitled
unknown
plain_text
a year ago
3.7 kB
25
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GearPart : MonoBehaviour
{
private GridSetup grid;
private GridItem gridItem;
private GameObject otherGearPart;
public int column;
public int row;
private Vector2 firstTouchPosition;
private Vector2 finalTouchPosition;
private Vector2 tempPosition;
public float swipeAngle = 0;
void Start()
{
grid = FindObjectOfType<GridSetup>();
gridItem = GetComponent<GridItem>();
column = gridItem.col;
row = gridItem.row;
}
public void MovePieces()
{
// Horizontal right swipe
if (swipeAngle > -45 && swipeAngle <= 45 && column < grid.width - 1)
{
// Get the right neighbor
otherGearPart = grid.allGearParts[column + 1, row];
if (otherGearPart != null)
{
SwapTiles(otherGearPart);
}
}
// Up swipe
else if (swipeAngle > 45 && swipeAngle <= 135 && row < grid.height - 1)
{
// Get the above neighbor
otherGearPart = grid.allGearParts[column, row + 1];
if (otherGearPart != null)
{
SwapTiles(otherGearPart);
}
}
// Horizontal left swipe
else if ((swipeAngle > 135 || swipeAngle <= -135) && column > 0)
{
// Get the left neighbor
otherGearPart = grid.allGearParts[column - 1, row];
if (otherGearPart != null)
{
SwapTiles(otherGearPart);
}
}
// Down swipe
else if (swipeAngle < -45 && swipeAngle >= -135 && row > 0)
{
// Get the below neighbor
otherGearPart = grid.allGearParts[column, row - 1];
if (otherGearPart != null)
{
SwapTiles(otherGearPart);
}
}
}
void SwapTiles(GameObject otherTile)
{
GearPart otherPart = otherTile.GetComponent<GearPart>();
// Save the target positions and rotations (current position and rotation of the other tile)
Vector2 tempPosition = otherTile.transform.position;
Quaternion tempRotation = otherTile.transform.rotation; // Save rotation
int tempCol = otherPart.column;
int tempRow = otherPart.row;
// Swap the tiles' transform positions and rotations
otherTile.transform.position = transform.position;
otherTile.transform.rotation = transform.rotation; // Swap rotation
transform.position = tempPosition;
transform.rotation = tempRotation; // Apply saved rotation to current tile
// Swap indices in the grid
grid.allGearParts[otherPart.column, otherPart.row] = gameObject;
grid.allGearParts[column, row] = otherTile;
otherPart.column = column;
otherPart.row = row;
column = tempCol;
row = tempRow;
}
private void OnMouseDown()
{
firstTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
private void OnMouseUp()
{
finalTouchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CalculateAngle();
}
void CalculateAngle()
{
swipeAngle = Mathf.Atan2(finalTouchPosition.y - firstTouchPosition.y, finalTouchPosition.x - firstTouchPosition.x) * 180 / Mathf.PI;
MovePieces();
}
}
Editor is loading...
Leave a Comment