- Home /
Moving ship to a point on keydown
Hi I'm having a problem. I have a ship that's in the middle of the screen. What I want to happen is when I hit the left arrow key the ship turns to the left a little and movers to the left of the screen, and when I hit the right key, it turns and moves to the right.
I know its most likely something really simple but Iv been killing myself the last two hours trying to get this to work. Anyone have any ideas?
what exactly are you trying to accomplish?
do you want the ship to move to the left / right while you are holding the button - or - do you want the ship to move to a certain worldposition when you press the button?
while holding the button i want the ship to move to a certain point and stay there until I let go, then it goes back to the middle point, if that makes any since.
yeah that sounds better.
do you want the ship to jump to the position or slowly move there? (btw. do you know iTween?)
give me a $$anonymous$$ute to write something down.
I just wanted to it go slowly there, yea but iTween isn't recognized whenever I make a new script Im most likely just doing it wrong?
did you download iTween from the asset store?
if not thats probably your problem.
Answer by senad · Feb 23, 2012 at 09:52 AM
Have a look at this tutorial, character movement is explained in it: http://unity3d.com/support/resources/tutorials/3d-platform-game
Thanx senad, Iv seen the tutorial before it helped me a lot with other parts of my game but not so much about this one, because my ship is more of an object that that just moves to a point when i hit a key then moves back when I let go.
Answer by ZweiD · Feb 23, 2012 at 12:02 PM
code in C#:
// put the following code in your Update function
float shipDistanceToCam = 10.0F;
// getting the 3 points the ship jumps to
Vector3 left = Camera.main.ScreenToWorldPoint(new Vector3(10,10,shipDistanceToCam));
Vector3 mid = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width/2,10,shipDistanceToCam));
Vector3 right = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width-10,10,shipDistanceToCam));
if(Input.GetKey("left")) {
gameObject.transform.position = left;
} else if(Input.GetKey("right")) {
gameObject.transform.position = right;
} else {
gameObject.transform.position = mid;
}
cannot test the code at the moment, so be carefull
with this the ship jumps to the coordinates.
if you want it to go slowly to the position, try doing something like:
iTween.$$anonymous$$oveTo(gameObject, left, 5);
ins$$anonymous$$d of setting the position directly. (documentation for iTween: http://itween.pixelplacement.com/documentation.php )