I have this code below which could control a touched player among 3 players. I was able to implement it by like sort of "cheating" by way of adding a 3D cube behind a 2D sprite since my game should be in 2D and I am having hard time implementing it in 2D. I'm really confused on how to do it in 2D because I'm really confuse on the parameters.
Although I already implemented it by the way mentioned above, I still want to implement it in pure 2D. And because I have this problem when the selected player moves, the sprite moves faster.
public GameObject target = null;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if(Input.touchCount > 0 || Input.GetTouch(0).phase == TouchPhase.Began)
{
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
Debug.DrawRay(ray.origin,ray.direction * 20,Color.red);
RaycastHit hit;
if(Physics.Raycast(ray, out hit,Mathf.Infinity))
{
Debug.Log(hit.transform.gameObject.name);
if(this.target != null){
SelectMove sm = this.target.GetComponent<SelectMove>();
if(sm != null){ sm.enabled = false; }
}
target = hit.transform.gameObject;
//Destroy(hit.transform.gameObject);
selectedPlayer();
}
}
}
void selectedPlayer(){
SelectMove sm = this.target.GetComponent<SelectMove>();
if(sm == null){
target.AddComponent<SelectMove>();
}
sm.enabled = true;
}
use RaycastHit2D to do this instead of RaycastHit then change Physics.Raycast to Physics2D.Raycast. The parameters are different the code below should do it.You may also have to change && to || depending on your game logic.
Select the Sprite then add Box Colider 2D from the Editor. You can also use Circle Collider 2D for the Sprite if your Sprite is round. If you don't add any 2D collider to the Sprite, ray won't detect the object when clicked on.
FOR MOBILE DEVICES
if ((Input.touchCount > 0) && (Input.GetTouch(0).phase == TouchPhase.Began))
{
Vector2 cubeRay = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D cubeHit = Physics2D.Raycast(cubeRay, Vector2.zero);
if (cubeHit)
{
//We hit something
Debug.Log(cubeHit.transform.gameObject.name);
if (this.target != null)
{
SelectMove sm = this.target.GetComponent<SelectMove>();
if (sm != null) { sm.enabled = false; }
}
target = cubeHit.transform.gameObject;
//Destroy(cubeHit.transform.gameObject);
selectedPlayer();
}
}
FOR DESKTOPS / EDITOR
if (Input.GetMouseButtonDown(0))
{
Vector2 cubeRay = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D cubeHit = Physics2D.Raycast(cubeRay, Vector2.zero);
if (cubeHit)
{
//We hit something
Debug.Log(cubeHit.transform.gameObject.name);
if (this.target != null)
{
SelectMove sm = this.target.GetComponent<SelectMove>();
if (sm != null) { sm.enabled = false; }
}
target = cubeHit.transform.gameObject;
//Destroy(cubeHit.transform.gameObject);
selectedPlayer();
}
}
来源:https://stackoverflow.com/questions/36417196/convert-3d-raycast-to-raycast2d