Question by
blastback27 · Dec 16, 2018 at 09:44 PM ·
rotationmovementraycastdirectionmouseposition
How can I incorporate a Rotation Towards the Mouse Position into this Script? I Tried.
I made a script so that my character would travel to my mouse position with raycast and such. Now I also want it to rotate itself towards my mouse positions.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PlayerMovement : MonoBehaviour
{
public float speed = 10f;
private Vector3 targetPos;
private Vector3 startPos;
private Vector3 mousePos;
public void Start()
{
startPos = transform.position;
}
public void Update()
{
if (Input.GetMouseButton(0))
{
mousePos = Input.mousePosition;
Ray mouseCast = Camera.main.ScreenPointToRay(mousePos);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
RaycastHit hit;
float rayLength;
if (Physics.Raycast(mouseCast, out hit, 100))
{
targetPos = new Vector3(hit.point.x, 2f, hit.point.z);
}
if (groundPlane.Raycast(mouseCast, out rayLength))
{
Vector3 pointToLook = mouseCast.GetPoint(rayLength);
transform.LookAt(new Vector3(pointToLook.z, transform.position.y, pointToLook.z));
}
transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
}
}
}
This part of the script is where I tried to incorporate the Rotation function.
float rayLength;
if (groundPlane.Raycast(mouseCast, out rayLength))
{
Vector3 pointToLook = mouseCast.GetPoint(rayLength);
transform.LookAt(new Vector3(pointToLook.z, transform.position.y, pointToLook.z));
}
It did not worked as planned. It rotate but not accurately with the mouse and sometimes not according or even the opposite direction of the mouse.
rttt.png
(287.3 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612184123im_/https://answers.unity.com/themes/thub/images/avi.jpg)