I know that this have been asked so much, but cant seem to find the answers on other post.
I got a Capsule(Player), and i want it to move to where the raycast hit the floor. My player have Character Controller attached. So when i press the left mouse button, I cast a ray from the camera to the mouse position, and then i know where hit.point(Physics.Raycast) is. But how i now move my Player with character controller to the hit.point?
Here is a Screenshot from the game, that blue ray is where the player should move:
Here is the code of the player:
using UnityEngine;
using System.Collections;
public class PlayerControl : MonoBehaviour
{
//Handling
public float walkSpeed = 5;
public float gravity = 8;
//Controllers
public Camera cam;
private CharacterController controller;
// Use this for initialization
void Start()
{
controller = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Vector3 mousePos = Input.mousePosition;
Ray mouseRay = cam.ScreenPointToRay(mousePos);
RaycastHit hit = new RaycastHit();
//If Right mouse button is pressed.
if (Input.GetMouseButtonDown(1)){
if(Physics.Raycast(mouseRay, out hit, 100))
{
//Ray for visual guide from camera to mouse position.
Debug.DrawRay(mouseRay.origin,mouseRay.direction*hit.distance,Color.red,1);
Debug.Log("Hitpoint: "+hit.point);
//This ray is just for a visual guide of where the raycasthit, hit.
Ray testRay = new Ray(hit.point,Vector3.up);
Debug.DrawRay(testRay.origin,testRay.direction,Color.blue,5);
}
}
//Gravity with character controller
Vector3 motion = new Vector3();
motion.y -= gravity;
controller.Move(motion*Time.deltaTime);
}
}