Question by
AGhostInTheFog · Oct 17, 2018 at 09:03 PM ·
c#2dplayer movementmovetowards
Sprite not moving properly?
I'm currently working on my first game in Unity making a 2D sidescroller. I'm trying to use the Vector2.MoveTowards() function but instead of moving up or down on key input, it moves down and left as soon as I run the game and I can't figure out why
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float Ymove;
public float speed;
void Start ()
{
}
private void Update()
{
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
if (Input.GetKeyUp(KeyCode.UpArrow))
{
targetPos = new Vector2(transform.position.x, transform.position.y + Ymove);
}
else if (Input.GetKeyDown(KeyCode.DownArrow))
{
targetPos = new Vector2(transform.position.x, transform.position.y - Ymove);
}
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612180506im_/https://answers.unity.com/themes/thub/images/avi.jpg)