olios
olios

Reputation: 69

Move object to Vector3 position with keeping gravity

I have such a problem, maybe someone will help. I am making a game and I need to make a dice that goes in the direction opposite to the click. For example, clicking on the back of a cube moves it forward, etc. Gravity must act on the cube as shown in the figure below. Unfortunately, the cube does not change height, but only the position of X and Z. Please help.

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCube : MonoBehaviour
{
Vector3 movePosition;
public float time = 0.02f;

[HideInInspector]
public bool blockClick = false;

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

private void Update()
{
    blockClick = false;

    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit raycastHit;

        if (Physics.Raycast(ray, out raycastHit))
        {
            string hitName = raycastHit.transform.name;

            if (hitName == "MoveCube")
            {
                move(raycastHit);
                blockClick = true;
            }
        }
    }

    transform.position = Vector3.Lerp(
            transform.position,
            movePosition,
            time);
}

public void move(RaycastHit raycastHit)
{
    Vector3 incomingVec = raycastHit.normal - Vector3.up;

    // South
    if (incomingVec == new Vector3(0, -1, -1))
    {
        movePosition = movePosition + new Vector3(0, 0, 1);
        return;
    }

    // North
    if (incomingVec == new Vector3(0, -1, 1))
    {
        movePosition = movePosition + new Vector3(0, 0, -1);
        return;
    }

    // West
    if (incomingVec == new Vector3(-1, -1, 0))
    {
        movePosition = movePosition + new Vector3(1, 0, 0);
        return;
    }

    // East
    if (incomingVec == new Vector3(1, -1, 0))
    {
        movePosition = movePosition + new Vector3(-1, 0, 0);
        return;
    }
}
}

enter image description here

Upvotes: 0

Views: 302

Answers (1)

atwillc
atwillc

Reputation: 1

From what I know, changing the transform.position of a gameObject with a rigidbody will mess with Unity's physics, and it won't work as intended. I suggest trying to apply a force from the position of the mouse's click instead of moving the cube's position manually (if this makes sense to do for your purposes). Here is the documentation for Rigidbody.AddForce

Upvotes: 0

Related Questions