Move object towards mouse position

Hey people ! I’m quite new at unity, so I’m trying out some scripting.

Basically my intent is to have a spaceship controlled with the WASD keys and having it always pointing to the position of the mouse. All of that in 3D isometric view.

Now I managed to get my spaceship moving with the WASD keys easily enough, and I managed to make it always look at the mouse, in two sepatate scripts.

My problem is that the WASD movements are relative to the position of the spaceship in the world, and not relative to the mouse’s position.

Basically, I want the spaceship’s movements to always be depending on the mouse. Forward should mean towards the mouse, not just towards a general direction.

Here’s my code

using UnityEngine;
using System.Collections;

public class LookAt : MonoBehaviour {


	public float speed;
	RaycastHit hit;
	Plane ground;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
		ground = new Plane(Vector3.up, transform.position);
		
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		
		float dist = 0.0f;
				
		if(ground.Raycast(ray,out dist)){
			Vector3 clickPoint = new Vector3(ray.GetPoint(dist).x, transform.position.y, ray.GetPoint(dist).z);
			
			Quaternion targetRotation = Quaternion.LookRotation(clickPoint - transform.position);
			
			transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
		
	}
}
}

I looked around the forums, but couldn’t find a solution, wat do?

Thank you for your answer in advance, preferably in C# :slight_smile:

gameobject.transform.forward

all objects have a position all objects with a transform have a transform object

all transform objects have .forward function which is forward RELATIVE TO there own local axis.

for a first person ship you want to attach the script to the camera and do

this.transform.forward

alternately you can do

Camera.main.transform.forward from within any script assuming your camera is tagged as main.

im just confused as to whether this is a first person or 3rd person view

first person you want to move towards camera.transform.forward

third person you can simply rotate the ship towards the pointer as you have said you already did then use the ships forward that is.

ship.transform.position += ship.transform.forward * speed * time.deltatime

if you need any further help implementing feel free to ask in comment