触屏游戏中如何判断点击的位置的左右
我们先要有一个可以反馈我们此时触控位置的输出参数。
我们在对应角色的脚本里获取它
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayController : MonoBehaviour
{
//获取触碰的位置
private Vector2 touchPosition;
public void GetTouchPosition(InputAction.CallbackContext context)
{
//因为 context.ReadValue<Vector2>() 拿过来的是点击的像素点位置而不是我们要的坐标点位置
//所以我们要将它的像素点位置转化为坐标点位置
touchPosition = Camera.main.ScreenToWorldPoint(context.ReadValue<Vector2>());
Debug.Log(touchPosition);
}
}
这样就可以获取我们要的坐标,以此就可以来判断对应的触屏位置关系。
使用获取到的触碰坐标来进行左右移动
思路是获取到对应的坐标,然后用获取到的坐标减去当前的位置,之后用得到的数值进行判断,使用枚举保存结果,之后修改对象的坐标。
//创建枚举,用来表示当前是向哪里操作
private enum Direction {
Up, Left, Right
}
//记录此时的点击位置
private Direction dir;
//获取到点击屏幕的坐标
touchPosition = Camera.main.ScreenToWorldPoint(context.ReadValue<Vector2>());
//用获取到的坐标减去触屏位置,之后用枚举值储存对应的结果
var offset = ((Vector3)touchPosition - transform.position).normalized;
if (Mathf.Abs(offset.x) <= 0.7f)
{
dir = Direction.Up;
}
else if (offset.x < 0)
{
dir = Direction.Left;
}
else if (offset.x > 0)
{
dir = Direction.Right;
}
//根据枚举值来进行对应的位移(moveDistance是设置好的固定值)
switch (dir)
{
case Direction.Up:
anim.SetBool("isSide", false);
destination = new Vector2(transform.position.x, transform.position.y + moveDistance);
break;
case Direction.Right:
anim.SetBool("isSide", true);
destination = new Vector2(transform.position.x + moveDistance, transform.position.y);
break;
case Direction.Left:
anim.SetBool("isSide", true);
destination = new Vector2(transform.position.x - moveDistance, transform.position.y);
break;
}
//将对应实体的坐标设置为我们需要的位置值
private Rigidbody2D rb;
rb.position = Vector2.Lerp(transform.position, destination, 0.134f);
通过反转对象,让左侧运动的动画应用于右侧运动
试想一个场景,我们已经做好了想做运动的动画,此时,我们想做一个只是x轴反转的向右运动的动画。
我们就不要傻乎乎的再做一遍啦,直接翻转就可以。
switch (dir)
{
//向前
case Direction.Up:
//不翻转,保持原样
transform.localScale = Vector3.one;
break;
//向右
case Direction.Right:
//翻转
transform.localScale = new Vector3(-1, 1, 1);
break;
//向左
case Direction.Left:
transform.localScale = Vector3.one;
break;
}
通过代码改变图层覆盖顺序(Sorting Layer)
、
sr.sortingLayerName = "center";//改覆盖顺序的
private SpriteRenderer sr;
//获取,别忘了!!!
private void Awake()
{
//获取覆盖图层的
sr = GetComponent<SpriteRenderer>();
}
//修改
sr.sortingLayerName = "center";