Moving player to mouse click, falling through scene

Hi

So I have a Cube/box collider as my Player.

I have already applied a JS onto it to make it constantly move forward in my scene.
The ground is just a cube/box collider scaled out.

Here’s what I have already on the object:

#pragma strict

function Start () {

}

function Update () {
	transform.Translate(15 * Vector3.forward * Time.deltaTime, Space.World);
}

Now I tried to attach a new second script to make the object move to where ever I click at on the ground (while it’s still constantly moving forward)…

but it makes my object instead start falling through the ground and moves upward.
As you can immediately see I have zero coding knowledge but I’m trying to learn :slight_smile:

#pragma strict

private var target:Vector3;

function Update () {
	if (Input.GetMouseButtonDown(0)) {
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            target.z = transform.position.z;
        }
        transform.position = Vector3.MoveTowards(transform.position, target, 10 * Time.deltaTime);
}

What i’m trying to achieve is to setup a standard top down scrolling airplane shooter game. That’s why I have the constant-move-forward applied so it moves through the scene/level. I want to be able to move the player around within the screen while the level scene “scrolls” through.

If anyone can even help show me a better way to write this I’d be so appreciative.
Thanks!

To understand this better it would be helpful to know if your camera is angled in such a way that Positive Y is the forward direction of your space ship or if it’s positive Z.

What is likely happening is that because Input.mousePosition is a 2d vector, your 3d vector has its Y value where its Z value should be.

That would be my guess.

To rectify this you need something like:

#pragma strict
 
private var target:Vector3;
private var tempX:float;
private var tempY:float;
private var tempZ:float;
 
5.function Update () {
    if (Input.GetMouseButtonDown(0)) {
            tempX = Camera.main.ScreenToWorldPoint(Input.mousePosition.x);
            tempY = transform.position.z;
			tempZ = Camera.main.ScreenToWorldPoint(Input.mousePosition.y);
			target = new Vector3(tempX, tempY, tempZ);
        }
10.        transform.position = Vector3.MoveTowards(transform.position, target, 10 * Time.deltaTime);
}

(my apologies if this isn’t accurate on line8. Im a C# user not a javascript user so I don’t know if jacascript needs to use the word ‘new’ before the vector3).