How can I use a 'grabber' to move objects in Unity (2D)?
Hi, so I'm trying to use a grab box to move objects on a 2d grid. The grabber can move on the 8x8 grid, and will be able to select what is currently under it.
Are there any hints you can give as to how I can implement this? Right now all I have is a control built into my grabber object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovementScript : MonoBehaviour {
public Vector2[][] myArray = new Vector2[8][];
int yVal = 0;
int xVal = 0;
// Use this for initialization
void Start () {
print("Hello World");
transform.position = new Vector3(0, 0, -10);
for (int i = 0; i < 8; i++)
{
myArray[i] = new Vector2[8];
for (int n = 0; n <8; n++)
{
myArray[i][n] = new Vector2(i, n);
}
}
print("Array initialized.");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown("up"))
{
if (yVal < 7) {
yVal++;
transform.position = new Vector2(myArray[xVal][yVal].x, myArray[xVal][yVal].y);
}
}
if (Input.GetKeyDown("down"))
{
if (yVal > 0)
{
yVal--;
transform.position = new Vector2(myArray[xVal][yVal].x, myArray[xVal][yVal].y);
}
}
if (Input.GetKeyDown("left"))
{
if (xVal > 0)
{
xVal--;
transform.position = new Vector2(myArray[xVal][yVal].x, myArray[xVal][yVal].y);
}
}
if (Input.GetKeyDown("right"))
{
if (xVal < 7)
{
xVal++;
transform.position = new Vector2(myArray[xVal][yVal].x, myArray[xVal][yVal].y);
}
}
}
}
So right now just the basic movement functions.
Answer by Fockducker11 · Oct 23, 2017 at 10:22 AM
Your code make everything so complicate. Can you explain your code please? I can't understand at all? Is this a grabber script or the object?
Your answer
![](https://koobas.hobune.stream/wayback/20220612141637im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I move a game object only on the x axis with arrow keys? 1 Answer
How to make bullet move? 0 Answers
Issues with dropping an object on multiple objects separetly - Simple 2d Drag & Drop 0 Answers
DontDestroyOnLoad not working properly on build (i think thats the problem atleast) 0 Answers
I can't do jump in my 2D game 1 Answer