- Home /
Question by
Serinplay · Aug 06, 2019 at 05:49 PM ·
rotationmovement scriptspaceshipclick to move
Space Game - Click To Move and Mouse Look
Hello Everybody,
I use this script for my space game project.But i have a problem.I need your helps.
Problem : My ship always looking the mouse position.I dont want this.I want when im clickin mouse button 1 , my ship must rotate and go where im clicked , smootly.
Thanks.
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed;
public GameObject camera;
void Update()
{
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if (playerPlane.Raycast(ray, out hitDist))
{
Vector3 targetPoint = ray.GetPoint(hitDist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
targetRotation.x = 0;
targetRotation.z = 0;
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 7f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.Mouse0))
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
}
}
[1]: /storage/temp/144171-asdasd.png
[2]: /storage/temp/144172-axsd.png
Comment
Best Answer
Answer by Hellium · Aug 07, 2019 at 07:21 AM
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float movementSpeed;
private new Camera camera;
private Vector3 destination;
private bool movingToDestination;
private void Start()
{
camera = Camera.main;
}
void Update()
{
if (Input.GetKey(KeyCode.Mouse0))
{
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = camera.ScreenPointToRay(Input.mousePosition);
float hitDist = 0.0f;
if (playerPlane.Raycast(ray, out hitDist))
{
destination = ray.GetPoint(hitDist);
destination.y = transform.position.y;
movingToDestination = true;
}
}
if( movingToDestination )
{
Quaternion targetRotation = Quaternion.LookRotation(destination - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 7f * Time.deltaTime);
transform.Translate(Vector3.forward * movementSpeed * Time.deltaTime);
movingToDestination = Vector3.SqrMagnitude(transform.position - destination) > 0.01f;
}
}
}