Question by
HAJFAJV · Aug 21, 2021 at 10:25 AM ·
2dmovementphysics2dmovement scriptmove an object
Making 2d grid movement
What do I need to change in order to move 1 unit at the time?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridMovementTest : MonoBehaviour
{
[SerializeField] private float moveSpeed = 1f;
//[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 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);
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);
moveCharacter(movement);
}
private void Update()
{
if ((hitleft.collider == null) && Input.GetAxisRaw("Horizontal") < 0)
{
movement = Vector2.left;
}
if ((hitright.collider == null) && Input.GetAxisRaw("Horizontal") > 0)
{
movement = Vector2.right;
}
if ((hitdown.collider == null) && Input.GetAxisRaw("Vertical") < 0)
{
movement = Vector2.down;
}
if ((hitup.collider == null) && Input.GetAxisRaw("Vertical") > 0)
{
movement = Vector2.up;
}
}
void moveCharacter(Vector2 direction)
{
if (Input.GetAxisRaw("Horizontal") < 0)
{
_rigidbody2D.MovePosition((Vector2)transform.position + (Vector2.left * moveSpeed * Time.deltaTime));
}
if (Input.GetAxisRaw("Horizontal") > 0)
{
_rigidbody2D.MovePosition((Vector2)transform.position + (Vector2.right * moveSpeed * Time.deltaTime));
}
if (Input.GetAxisRaw("Vertical") < 0)
{
_rigidbody2D.MovePosition((Vector2)transform.position + (Vector2.down * moveSpeed * Time.deltaTime));
}
if (Input.GetAxisRaw("Vertical") > 0)
{
_rigidbody2D.MovePosition((Vector2)transform.position + (Vector2.up * moveSpeed * Time.deltaTime));
}
}
}
Comment