HELP! RigidBody2D position is acting incredibly goofy!!
Thank you to whoever is taking the time to help me out right now.
So basically, what I am attempting to do is make a top-down, grid-based game, where a highlighting box will light up tiles according to where the mouse's position is, basically imagine the highlighting box moving on a grid, where it does not smoothly follow the mouse, it snaps to the next grid position. I use rb.position to handle this and use the mouse's distance to determine if the mouse is far enough from the box's position for the box to snap to the next position.
The problem that I am having has to do with all of my if statements, when I comment out the if statements that concern the y axis movement, the x axis will snap and move as desired, and vice versa. HOWEVER, when I leave all four if statements active, it begins to act incredibly buggy, where the highlighting box will snap around crazily, I have tried using several if-else statements in all kinds of combinations, I tried making two scripts where each axis movement is handled individually, but nothing is working.
I appreciate any help that anyone is willing to give!!
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SelectionColliderScript1 : MonoBehaviour { public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
float dist = Vector2.Distance(gameObject.transform.position, mousePosition);
Debug.Log("The distance is " + dist);
if (dist > 0.51f && mousePosition.x > gameObject.transform.position.x)
{
rb.position = new Vector2(transform.position.x + 1f, transform.position.y);
}
if (dist > 0.51f && mousePosition.x < gameObject.transform.position.x)
{
rb.position = new Vector2(transform.position.x - 1f, transform.position.y);
}
if (dist > 0.51f && mousePosition.y > gameObject.transform.position.y)
{
rb.position = new Vector2(transform.position.x, transform.position.y + 1f);
}
if (dist > 0.51f && mousePosition.y < gameObject.transform.position.y)
{
rb.position = new Vector2(transform.position.x, transform.position.y - 1f);
}
}
}
Your answer
Follow this Question
Related Questions
Rigidbody2D doesn't fall correctly when using MovePosition to move it horizontally 0 Answers
Vector2 always becomes (1, 1), even if manully set to (0, 0)? 0 Answers
My sprite looks like it is haveing a seizure. What am I doing wrong? 1 Answer
How do I keep enemies (rigidbodies) from pushing each other? 1 Answer