- Home /
Question by
HAJFAJV · Aug 24, 2021 at 08:28 AM ·
2dphysics2dphysics.raycast
Moving one square at the time with velocity
Hello
Third script. I'm using rigidbody2d and velocity instead of moving the transform, I didn't know physics didnøt work with the previous methods. Now however I don't know to to stop my character again so it only moves one square at the time.
I'm working on a topdown 2d game and want to use boxcast to check for collisions with the environment, instead of the overlapcircle I'm using right now. I have up, down, left, and right movement on a grid each 32px squares so 0.32 of a Unity unit I believe.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridMovementTest : MonoBehaviour
{
[SerializeField] private float moveSpeed = 4f;
//[SerializeField] private Transform movePoint;
//[SerializeField] private Animator anim;
[SerializeField] private LayerMask cannotMoveTo;
private BoxCollider2D boxCollider2D;
private Rigidbody2D _rigidbody2D;
private RaycastHit2D hitdown, hitup, hitleft, hitright;
private Vector2 movement;
void Start()
{
//movePoint.parent = null;
boxCollider2D = this.GetComponent<BoxCollider2D>();
_rigidbody2D = this.GetComponent<Rigidbody2D>();
}
/*void OnDrawGizmos()
{
Gizmos.color = new Color(1, 0, 1, .5f);
Gizmos.DrawCube(movePoint.position, new Vector2(.32f, .32f));
}*/
void FixedUpdate()
{
RaycastHit2D hitdown = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.down, .32f, cannotMoveTo);
RaycastHit2D hitup = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.up, .32f, cannotMoveTo);
RaycastHit2D hitleft = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.left, .32f, cannotMoveTo);
RaycastHit2D hitright = Physics2D.BoxCast(boxCollider2D.bounds.center, boxCollider2D.bounds.size, 0f, Vector2.right, .32f, cannotMoveTo);
moveCharacter(movement);
}
private void Update()
{
if ((hitleft.collider == null) && Input.GetAxisRaw("Horizontal") < 0)
{
movement = Vector2.left * .32f;
}
if ((hitright.collider == null) && Input.GetAxisRaw("Horizontal") > 0)
{
movement = Vector2.right * .32f;
}
if ((hitdown.collider == null) && Input.GetAxisRaw("Vertical") < 0)
{
movement = Vector2.down * .32f;
}
if ((hitup.collider == null) && Input.GetAxisRaw("Vertical") > 0)
{
movement = Vector2.up * .32f;
}
}
void moveCharacter(Vector2 direction)
{
_rigidbody2D.velocity = direction * moveSpeed;
}
}
Comment
If you're using grid based movement, then why bother using a rigidbody2D? If your character doesn't use physics at all then just stick to moving its transform.position.
Your answer