Question by
unity_Cbad70pIwzpV0g · Apr 02, 2020 at 01:51 AM ·
movementgameobjectphysics2d gametouch
Player Only Moves When I Touch The GameObject Directly But I Want To Touch And Move From Anywhere From The Screen,Player Moves By Touch but ONLY When I Touch The GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private GameManager gm;
[Header("Rigidbody And Collider")]
private Rigidbody2D rb2d;
private Collider2D c2d;
[Space]
[Header("Floats, Ints And Bools")]
public float startSpeed = 1f;
public float speed;
private float playerMoveSpeed = 12f;
private const float acceleration = 0.1f;
private float currentSpeed;
private float deltaX, deltaY;
[Space]
[Header("Vectors")]
private Vector3 touchPosition;
private Vector3 direction;
void Start()
{
gm = FindObjectOfType<GameManager>();
rb2d = gameObject.GetComponent<Rigidbody2D>();
c2d = gameObject.GetComponent<Collider2D>();
speed = startSpeed;
}
void FixedUpdate()
{
ClampScreen();
MovePlayerTouchScreen();
MoveUp();
}
public void MovePlayerTouchScreen()
{
if (Input.touchCount > 0 && gm.PlayerStatus() == false && gm.respawned == true)
{
Touch touch = Input.GetTouch(0);
touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
switch (touch.phase)
{
case TouchPhase.Began:
deltaX = touchPosition.x - transform.position.x;
break;
case TouchPhase.Moved:
rb2d.MovePosition(new Vector2(touchPosition.x - deltaX, 0f) * playerMoveSpeed);
break;
case TouchPhase.Ended:
rb2d.velocity = Vector2.zero;
break;
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How to restrict object's movement to a bezier curve? 0 Answers
How to determine if a GameObject is being shaken? 0 Answers
Player Win and Display on-screen restart options and start menu 2D game 0 Answers
I don't want the arms to turn with the ball at my game 0 Answers
Unity 2D Enemy movement problems 2 Answers