C# 无论您在IOS设备上触按何处,Unity project角色都只能单向移动
这是我在unity中创建的2D游戏中触摸IOS设备时的移动代码。但当我运行它时,游戏会加载,但当我触到右侧时,他会向左移动,当我触到左侧时,他也会向左移动 我已经使用了ScreenToWorldPoint,但它似乎不起作用,他只会朝一个方向移动C# 无论您在IOS设备上触按何处,Unity project角色都只能单向移动,c#,ios,unity3d,2d,C#,Ios,Unity3d,2d,这是我在unity中创建的2D游戏中触摸IOS设备时的移动代码。但当我运行它时,游戏会加载,但当我触到右侧时,他会向左移动,当我触到左侧时,他也会向左移动 我已经使用了ScreenToWorldPoint,但它似乎不起作用,他只会朝一个方向移动 void PlayerWalkMobile() { // force by which we will push the player float force = 0.0f; // the players velocity
void PlayerWalkMobile()
{
// force by which we will push the player
float force = 0.0f;
// the players velocity
float velocity = Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x);
if (Input.touchCount > 0)
{
countTouches++;
Touch h = Input.touches[0];
Vector2 position = Camera.main.ScreenToWorldPoint(new Vector2(h.position.x, h.position.y));
Debug.Log("the postion of the touch is " + h.position);
if (position.x > 0)
{
// if the velocity of the player is less than the maxVelocity
if (velocity < maxVelocity)
force = speed;
// turn the player to face right
Vector3 scale = transform.localScale;
scale.x = 1;
transform.localScale = scale;
// animate the walk
animator.SetInteger("walk", 1);
}
else if (position.x < 0)
{
// if the velocity of the player is less than the maxVelocity
if (velocity < maxVelocity)
force = -speed;
// turn the player to face right
Vector3 scale = transform.localScale;
scale.x = -1;
transform.localScale = scale;
// animate the walk
animator.SetInteger("walk", 1);
}
// add force to rigid body to move the player
GetComponent<Rigidbody2D>().AddForce(new Vector2(force, 0));
// set the idle animation
if (h.phase == TouchPhase.Ended)
animator.SetInteger("walk", 0);
} // if Input.touchCount > 0
}
本应以0.0为中心设置
scale.x=-1
是否反转方向?如果是这样的话,你也可以通过设置force=-speed
.scale.x=-1反转方向是正确的,它会使人转向另一个方向
Vector2 position = Camera.main.ScreenToWorldPoint(new Vector2(h.position.x, h.position.y));