- Home /
Cube glitches when it moves into wall
Hello! So I have a cube that when I press "W", it slides exactly +1 in the x position. It works fine right now, but when it runs into a wall, it goes in a little then starts to glitch and it can't move. Is there any way I can fix this bug? Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
public float speed = 1;
private Vector3 target;
// Use this for initialization
void Start () {
target = transform.position;
}
void Update () {
if (Input.GetKeyDown(KeyCode.A)) {
target += Vector3.forward;
} else if (Input.GetKeyDown(KeyCode.D)) {
target += Vector3.back;
} else if (Input.GetKeyDown(KeyCode.W)) {
target += Vector3.right;
} else if (Input.GetKeyDown(KeyCode.S)) {
target += Vector3.left;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
}
Answer by Neebz · Dec 16, 2017 at 11:06 PM
By moving using transform, you are basically ignoring the collisionbox on the object by teleporting it's position, and the object has no way of knowing if there is a wall ahead of it. Instead, you could set velocity on the rigidbody component, if you have that on. This will, by itself, check for collisions when moving around. However, this may not have the wanted effect, and so instead you could try using raycasts, in order to check whether a wall is in the direction you want to move, and if not, you can move the object.
Answer by Carson365 · Dec 16, 2017 at 11:14 PM
Thanks for the reply. I am a beginner so I am still working on raycasts, so I think I would modify velocity IF I can. Can you please help me on how I would change to velocity. It took me a while figuring out the code above, so changing to velocity might be a struggle. Thanks!
You could do it with this simple code:
public float speed = 1;
private Rigidbody rb;
private Vector3 moveDirection;
void Start() {
rb = GetComponent<Rigidbody>();
}
//Fixed update to handle physics calculations
void FixedUpdate() {
//Gets movement from input controls... left arrow and a sets the Horizontal input to -1, right arrow or D sets it to 1.
float horizontalFloat = Input.GetAxis("Horizontal");
float verticalFloat = Input.GetAxis("Vertical");
//$$anonymous$$akes a new vector for handling the movement direction
moveDirection = new Vector3(horizontalFloat, 0, verticalFloat);
//applies the movement vector
rb.velocity = (moveDirection * speed);
}
$$anonymous$$ake sure that you add a "Rigidbody" component to your object, and you're propably going to want to freeze the rotation on it, unless you want the object to rotate around as it moves :)
Thanks for the reply. So it works pretty well but I need the cube to move exactly +1 in the axis it needs to, such as X is 6 and then you press W and it will be 7.