- Home /
Question by
PruneDealer · Oct 05, 2019 at 04:05 PM ·
player movementboundary
Stopping player move towards button when pressed [2D]
I have a player movement script and a few buttons I need to activate from time to time. The buttons are outside of a box (playing field) and the player is inside. Currently the player just moves to wherever I touch, but is there a way to make the player only react to touches inside the playing field. Thanks a lot and sorry if the question was kind of confusing.
Player movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public int speed;
private Vector3 touchPosition;
private Rigidbody2D rb;
private Vector3 direction;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
speed = PlayerPrefs.GetInt("Speed", 16);
}
public static void Speed()
{
PlayerPrefs.GetInt("Speed", 16);
}
private void Update()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
touchPosition.z = 0;
direction = (touchPosition - transform.position);
rb.velocity = new Vector2(direction.x, direction.y) * speed;
if (touch.phase == TouchPhase.Ended)
rb.velocity = Vector2.zero;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Player boundaries based on screen resolution 1 Answer
How can I limit my 2D player movement along the Y-axis? 1 Answer
Calculate screen top and bottom postion 1 Answer
map, scene, world boundaries? 0 Answers
Generate obstacles within boundry 1 Answer