Question by
turfyiscool · Nov 25, 2018 at 05:54 PM ·
vector2movetowards
Vector2.MoveTowards not working.
hi. So i'm a noob to unity and i'm trying to make a simple 2D player movement script. All was working until i added a constraint to it. It works for horizontal movement but not vertical. Here is my code.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMovement : MonoBehaviour {
private Vector2 targetpos;
public float Yincrement;
public float Xincrement;
public float speed;
public int Maxhight;
public int Minhight;
public int Maxwidth;
public int Minwidth;
void Update () {
if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.y > Maxhight)
{
targetpos = new Vector2(transform.position.x, transform.position.y - Yincrement);
}else if (Input.GetKeyDown(KeyCode.UpArrow) && transform.position.y < Minhight)
{
targetpos = new Vector2(transform.position.x, transform.position.y + Yincrement);
}else if (Input.GetKeyDown(KeyCode.LeftArrow) && transform.position.x > Minwidth)
{
targetpos = new Vector2(transform.position.x - Xincrement, transform.position.y);
}else if (Input.GetKeyDown(KeyCode.RightArrow) && transform.position.x < Maxwidth)
{
targetpos = new Vector2(transform.position.x + Xincrement, transform.position.y);
}
transform.position = Vector2.MoveTowards(transform.position, targetpos, speed * Time.deltaTime);
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612182731im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How can I use Vector2.MoveTowards to UIElements 0 Answers
How to move more than one object together at a time? 1 Answer
How to use Vector2 movetowards? 1 Answer
Vector2.MoveTowards works strangely 0 Answers
Vector2.moveToward 0 Answers