- Home /
click to move script goes through objects
Hi. I have problem with this:
using UnityEngine; using System.Collections;
public class Click2Move : MonoBehaviour { public Camera PlayerCam; public Transform mover; //the object being moved public float SnapTo = 0.5f; //how close we get before snapping to the desination private Vector3 destination = Vector3.zero; //where we want to move
// Use this for initialization
void Start ()
{
destination = mover.position; //set the destination to the objects position when the script is run the first time
}
// Update is called once per frame
void Update()
{
//when left mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
Ray ray = (PlayerCam.ScreenPointToRay(Input.mousePosition)); //create the ray
RaycastHit hit; //create the var that will hold the information of where the ray hit
if (Physics.Raycast(ray, out hit)) //did we hit something?
if (hit.transform.name == "Ground") //did we hit the ground?
destination = hit.point; //set the destinatin to the vector3 where the ground was contacted
}
// move the object toward the destination
if (Vector3.Distance(mover.position, destination) < SnapTo) //are we within snap range?
mover.position = destination; //snap to destination
else
mover.position = Vector3.MoveTowards(mover.transform.position, destination, Time.deltaTime * 4); //move toward destination
}
}
Click2Move script.. Script works like this: Attach it to camera, put your player to "mover" and change snap to 0. Then drag your camera to "PlayerCam"..
And when you have object in front of you and you click to other side of it, player goes through object, even if object haves collider!
Please help me!
Lewenos
have you added a rigid body to you player If you dont want gravity just turn it off but I found it enables collisions.
hope this is helpful
Next time, highlight the code and push the lil 10101 button up top =). Thanks a lot! =D
Justin Warner: Oh, sure :)
Scribe: No, i will add, thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125158im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Click to move script, need help. 1 Answer
When near object, able player to click it and then player teleports. 1 Answer
Can I make a MMORPG with unity? 20 Answers
Quick Terrain Sizing Question! 0 Answers
Help with variables... 0 Answers