- Home /
How to make my spaceship move by mouse?
I am trying to make a game very similar to space shooters project. I am adding a few tweaks but the main problem I am having is that I cannot write a valid c# script for the spaceship movement. The game is in 2d, but I am using 3d models and 3d physics. I want to make spaceship move according to mouse position. I am kinda lost in scripting reference and I do not know what to use. Any suggestions, hints or examples would be very apreciated!
What code have you written so far? How do you want the mouse to effect the ship?
Answer by bilo-lwabona · Sep 14, 2014 at 07:18 PM
As you said, despite the 3d environment/content you can use 2D logic. With your axes of choice, e.g. x & y axes for horizontal and vertical movement (neglecting the z-axis) you could write a mapping between the mouse motion and the ship's motion. What you need is the following
Vector2 deltaMousePosition
... this will be adjusted in the update loop with Unity'sInput.GetAxis("Mouse X")
andInput.GetAxis("Mouse Y")
In your update loop add this deltaMousePosition to the ship's transform.position, but make sure to clamp it so it does not go off screen ( a simple if statements should suffice)
That is the basic solution. Hope this helps, otherwise please be more specific with your question.
Answer by dreg_master · Jan 09, 2019 at 04:48 AM
// Update is called once per frame
private void Update()
{
if (enableThis) Move();
}
private void Move()
{
//var deltaX = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
var deltaX = Input.GetAxis("Mouse X");
var newXPos = Mathf.Clamp(transform.position.x + deltaX, xMin, xMax);
transform.position = new Vector3(newXPos, transform.position.y, transform.position.z);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613163003im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
How to rotate Character on Y axis along with the mouse rotation? 0 Answers
Moving in the direction of mouse 3 Answers
Mouse Swipe and Code Efficiency 0 Answers
Multiple Cars not working 1 Answer