How to move character to touch Y location smoothly?
I know there are a lot of questions like this, but I can't seem to figure it out from any of them. I'm really new to this and have done lots of tutorials, so I'm trying to jump right in and make a 2D app in C#. Basically, I want the character to move to the Y point of a touch, but smoothly. Right now it jumps right to the point, but I want it to travel there over a second or two. I've tried Lerp and MoveTowards to no avail (possibly by doing it wrong, but I feel I've tried everything). What I would really like is for a YSpeed to be used on the character until the character gets to the touch Y position, then the YSpeed return to 0. I do not want the player's X position to be affected by this.
The following code has the player moving left or right based on what side of the screen the touch is on and going up or down to the touch Y position.
Also, my if statement for Up/Down is a little weird right now because I'm going to split it into two later on.
Any help would be greatly appreciated!
public class playerInput : MonoBehaviour {
public GameObject Player;
[SerializeField]
private float XSpeed =.05f;
[SerializeField]
private float YSpeed;
// Use this for initialization
void Start () {
GetComponent<SpriteRenderer>().flipX = false;
}
// Update is called once per frame
void Update () {
transform.Translate(XSpeed, YSpeed, 0);
for (var i = 0; i < Input.touchCount; ++i) {
var playerTouch = new Touch();
playerTouch = Input.GetTouch(i);
if (playerTouch.phase == TouchPhase.Began) {
//--------TOUCH LEFT---------
if (playerTouch.position.x < (Screen.width/2)) {
GetComponent<SpriteRenderer>().flipX = true;
XSpeed = -.05f;
}
//-------TOUCH RIGHT---------
if (playerTouch.position.x > (Screen.width/2)) {
GetComponent<SpriteRenderer>().flipX = false;
XSpeed = .05f;
}
//-------TOUCH UP---------
if (playerTouch.position.y > (Player.transform.position.y) || playerTouch.position.y < (Player.transform.position.y)) {
playerTouch.position = Camera.main.ScreenToWorldPoint(new Vector3 (playerTouch.position.x, playerTouch.position.y, 0));
Player.transform.position = new Vector3 (Player.transform.position.x, playerTouch.position.y, 0);
}
}
}
}
} `
Your answer
Follow this Question
Related Questions
Code help with mobile touch drag 3D Top Down 0 Answers
How to Move Character to a Touched position on mobile devices? 1 Answer
What is the correct way to move objects relative to each other ? 1 Answer
Up Velocity 1 Answer
i'm using a code to make my cube walk with character controller but when i play the cube spins. 0 Answers