- Home /
How to push an object in 2D grid style
Hello, i have a script for movement in tile based grid (1 cell per time) and i want to be able to push the objects that i collide a fix length too. Right now i'm able to to this by changing the position of the collide object but the movement is not smooth (cause is not moving per frame but instant). How can i adapt the code? Or there are better ways to reach this behavior?
I simply want that every object in my game only move in tiles, staying inside each cell.
Here is my code for movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class newMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Transform movepoint;
public LayerMask whatStopsMovement;
private Vector3 newPosition;
void Start()
{
movepoint.parent = null;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, movepoint.position, moveSpeed * Time.deltaTime);
if(Vector3.Distance(transform.position, movepoint.position) <= .05f){
float inputX = Input.GetAxisRaw("Horizontal");
float inputY = Input.GetAxisRaw("Vertical");
if(Mathf.Abs(inputX) == 1f){
newPosition = movepoint.position + new Vector3(inputX, 0f, 0f);
if(!Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement)){
movepoint.position = newPosition;
}else{
Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement).gameObject.transform.position = Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement).gameObject.transform.position + new Vector3(inputX, 0f, 0f);
}
}else if(Mathf.Abs(inputY) == 1f){
newPosition = movepoint.position + new Vector3(0f, inputY, 0f);
if(!Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement)){
movepoint.position = newPosition;
}else{
Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement).gameObject.transform.position = Physics2D.OverlapCircle(newPosition, .2f, whatStopsMovement).gameObject.transform.position + new Vector3(0f, inputY, 0f);
}
}
}
}
}
Your answer
Follow this Question
Related Questions
How To Create 2D Ragdoll Movement? 1 Answer
[2D] Moving the player 1 tile at a time using rigidbody movement 0 Answers
Help Me! I want to make a pixel fairy! 1 Answer
Two Polygon2D Collider do not Collide with Each Other (Solved) 2 Answers
2D player keeps getting dragged to the left for some reason. 0 Answers