Question by
UltraSkull · Apr 23, 2017 at 08:28 PM ·
movementmobilecharactertouch
How to Move Character to a Touched position on mobile devices?
I am making a Mobile-based Bullet hell game of which I am having trouble with making the player move with the touch of the screen. When the scren is touched, i would like for the player to be instantly transported to the coordinates of the touch. Based on other posts, this is the script I have accumulated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterControllerBH : MonoBehaviour {
public GameObject PlayerCharacter;
Vector3 touchpos;
public Vector3 playerpos;
void Update () {
Touch touch = Input.GetTouch(0);
touchpos = GetComponentInChildren<Camera>().ScreenToWorldPoint(touch.position);
playerpos = new Vector3(touchpos.x,1,touchpos.z);
PlayerCharacter.GetComponent<Transform>().position = playerpos;
}
}
However, when I use this, it simply Centers the Player in the center of the camera. I am not Sure why. Any Suggestions?
Before Touch After Touch
2017-04-23.png
(317.6 kB)
2017-04-23-1.png
(311.2 kB)
Comment
Answer by alph1 · Apr 28, 2017 at 10:15 AM
Try
touchpos = Camera.main.ScreenToWorldPoint(touch.position);
And
playerpos = new Vector2(touchpos.x,touchpos.y);
You dont have tweak the z component of your gameObject
also Define Vector3 touchpos
as Vector2 touchpos
as long as you dont need to change z component of any object use Vector2 instead of Vector3