Hello I have this script for moving object on single click
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pohyb : MonoBehaviour{
private GameObject aktivny;
private bool pohybuje_sa;
private float sila, rychlost, krok;
private float x, y, z;
private float lavo, pravo, vpred, vzad;
private Vector3 pozicia;
private Vector3 doLava, doPrava, doPredu, doZadu;
private Vector3 kurzor;
void Start()
{
krok = 2.0f;
sila = krok * 4;
rychlost = sila * Time.deltaTime;
}
void Update()
{
RaycastHit hit;
kurzor = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(kurzor);
if (Physics.Raycast(ray, out hit))
{
//Debug.Log("HITTING ALL");
if (hit.collider.tag == "Movable")
{
//Debug.Log("HITTING TAGGED");
if (Input.GetButtonDown("Fire1"))
{
//Debug.Log("CLICKING TAGGED");
aktivny = hit.transform.gameObject;
pohybuje_sa = true;
x = aktivny.transform.position.x;
y = aktivny.transform.position.y;
z = aktivny.transform.position.z;
pozicia = new Vector3(x, y, z);
lavo = x + krok;
pravo = x - krok;
vpred = z - krok;
vzad = z + krok;
doLava = new Vector3(lavo, y, z);
doPrava = new Vector3(pravo, y, z);
doPredu = new Vector3(x, y, vpred);
doZadu = new Vector3(x, y, vzad);
}
}
}
if (pohybuje_sa)
{
if (Input.GetKeyDown(KeyCode.A))
{
//Debug.Log("going left");
StartCoroutine(move(doLava));
}
else if (Input.GetKeyDown(KeyCode.D))
{
//Debug.Log("going right");
StartCoroutine(move(doPrava));
}
else if (Input.GetKeyDown(KeyCode.W))
{
//Debug.Log("going forward");
StartCoroutine(move(doPredu));
}
else if (Input.GetKeyDown(KeyCode.S))
{
//Debug.Log("going back");
StartCoroutine(move(doZadu));
}
}
}
IEnumerator move(Vector3 ciel)
{
while(true)
{
float distance = Vector3.Distance(pozicia, ciel);
if (distance > 0.0f)
{
//Debug.Log("Object moving from " + position + " to " + target);
pozicia = Vector3.MoveTowards(aktivny.transform.position, ciel, rychlost);
aktivny.transform.position = pozicia;
x = aktivny.transform.position.x;
y = aktivny.transform.position.y;
z = aktivny.transform.position.z;
pozicia = new Vector3(x, y, z);
lavo = x + krok;
pravo = x - krok;
vpred = z - krok;
vzad = z + krok;
doLava = new Vector3(lavo, y, z);
doPrava = new Vector3(pravo, y, z);
doPredu = new Vector3(x, y, vpred);
doZadu = new Vector3(x, y, vzad);
pohybuje_sa = false;
yield return null;
}
else
{
pohybuje_sa = true;
break;
}
}
}
}
And it’s working fine but the object gets stuck in wall collider if I move it through wall.
How to fix it ?
Is it because of Vector3.MoveTowards ?
And if yes what is good alternative ?