# Collision issue

Hello everyone !

I’m a beginner in Unity so please be indulgent

I would like to move a cube with the following keys : Z, Q, S, D
Z for up, S for down, Q for left and D for right on x and z axis.
And E for up and F for down on y axe.

My problem is the cube doesn’t take into account the collisions with other objects and pierce them.
I attached to this cube RigidBody and BoxCollider components.

Here is the code i use for the movement :

``````using UnityEngine;

public class CameraController : MonoBehaviour
{
public float speed = 20f;
// Cube position
Vector3 pos;
// Cube direction
Vector3 view;
// Way to go
Vector3 way;

private void Start()
{
pos = transform.position;
}

void Update()
{

view = transform.forward;
way = view * speed * Time.deltaTime;

if (Input.GetKey(KeyCode.Z))
pos += new Vector3(way.x, 0, way.z);

if (Input.GetKey(KeyCode.S))
pos += new Vector3(-way.x, 0, -way.z);

if (Input.GetKey(KeyCode.Q))
{
Vector2 temp = Vector2.Perpendicular(new Vector2(view.x, view.z));
view = new Vector3(temp.x, 0, temp.y);
way = view * speed * Time.deltaTime;
pos += new Vector3(way.x, 0, way.z);
}

if (Input.GetKey(KeyCode.D))
{
Vector2 temp = Vector2.Perpendicular(new Vector2(view.x, view.z));
view = new Vector3(temp.x, 0, temp.y);
way = view * speed * Time.deltaTime;
pos += new Vector3(-way.x, 0, -way.z);
}

if (Input.GetKey(KeyCode.E))
pos.y += speed * Time.deltaTime;

if (Input.GetKey(KeyCode.F))
pos.y -= speed * Time.deltaTime;

transform.position = pos;
}
}
``````

What I should to do in order to have the desired result ?

Thank you

Hi, and welcome to Unity forums!

You need to use a different approach. The object must be moved using Rigidbody.AddForce (not Transform) so the physics could handle the collisions. You may apply a velocity increment to the object with Rigidbody.AddForce(velocity, ForceMode.VelocityChange).

I’d do something like this:

• Figure out a normalized direction vector of the movement based on the keys. For example, if Z “up” is pressed, then the direction vector would be Vector3(0, 1, 0). If Z “up” and Q “left” are pressed, then the direction would be Vector3(-1, 1, 0).normalized. If no key is pressed then the direction vector would be 0,0,0.
• Compute the velocity the rigidbody should have. This would be simply: desiredVelocity = direction * speed. Note that we’re specifying the velocity directly instead of the distance to move, so no Time.deltaTime is used.
• Apply the desired velocity taking into account the current velocity the rigidbody is moving at. The velocity difference can be computed by subtracting the current velocity from the desired velocity, so it would be like this: