我使用下面的代码我可以移动我的角色并将其限制在摄像机视图中。但由于我正在使用输入Input.GetAxisRaw ("Horizontal");
,我的角色会使用a-d键和箭头键移动。但我想要另一个角色的箭头键。
我尝试AddForce
(我不喜欢字符移动)和if语句来使用特定的键。但我无法使用我的代码检查边界。你能提出什么建议吗? (顺便说一句,我的角色只能水平移动)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBlueController : MonoBehaviour {
public float speed;
public Rigidbody2D player1rb;
public float viewpointfirst;
public float viewpointsecond;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
float horizontal = Input.GetAxisRaw ("Horizontal");
if((horizontal > 0) || (horizontal < 0))
{
Vector3 tempVect = new Vector3 (horizontal, 0, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
Vector3 newPos = player1rb.transform.position + tempVect;
checkBoundary (newPos);
}
}
void checkBoundary(Vector3 newPos)
{
Vector3 camViewPoint = Camera.main.WorldToViewportPoint (newPos);
camViewPoint.x = Mathf.Clamp (camViewPoint.x, viewpointfirst, viewpointsecond);
Vector3 finalPos = Camera.main.ViewportToWorldPoint (camViewPoint);
player1rb.MovePosition (finalPos);
}
}
答案 0 :(得分:1)
修改旧版answer以使用Input.GetKey
代替Input.GetAxisRaw
。您所要做的就是在向左移动时将Vector3 (horizontal, 0, 0);
的水平变量替换为-1
,向右移动时替换为1
,而在未按下时将0
替换为Update
。其余代码保持不变。我添加了更多函数来防止多次编写相同的代码,因为你希望 player 1 和 player 2 使用不同的密钥,这需要相同的代码。
播放器1 的WASD和播放器2 的箭头键。您可以在调用movePlayer
的{{1}}函数中将这些更改为您想要的任何键。
public float speed = 50;
public Rigidbody2D rb1;
public Rigidbody2D rb2;
public void Update()
{
//Player one (WASD)
movePlayer(rb1, KeyCode.A, KeyCode.D, KeyCode.W, KeyCode.S);
//Player two (Arrow keys)
movePlayer(rb2, KeyCode.LeftArrow, KeyCode.RightArrow, KeyCode.UpArrow, KeyCode.DownArrow);
}
void movePlayer(Rigidbody2D targetRg, KeyCode left, KeyCode right, KeyCode up, KeyCode down)
{
Vector2 hAndV = getInput(targetRg, left, right, up, down);
Vector3 tempVect = new Vector3(hAndV.x, hAndV.y, 0);
tempVect = tempVect.normalized * speed * Time.deltaTime;
Vector3 newPos = targetRg.transform.position + tempVect;
checkBoundary(targetRg, newPos);
}
Vector2 getInput(Rigidbody2D targetRg, KeyCode left, KeyCode right, KeyCode up, KeyCode down)
{
Vector2 input = Vector4.zero;
//Horizontal
if (Input.GetKey(left))
input.x = -1;
else if (Input.GetKey(right))
input.x = 1;
else
{
input.x = 0;
targetRg.velocity = Vector3.zero;
targetRg.angularVelocity = 0f;
}
//Vertical
if (Input.GetKey(up))
input.y = 1;
else if (Input.GetKey(down))
input.y = -1;
else
{
input.y = 0;
targetRg.velocity = Vector3.zero;
targetRg.angularVelocity = 0f;
}
return input;
}
void checkBoundary(Rigidbody2D targetRg, Vector3 newPos)
{
//Convert to camera view point
Vector3 camViewPoint = Camera.main.WorldToViewportPoint(newPos);
//Apply limit
camViewPoint.x = Mathf.Clamp(camViewPoint.x, 0.04f, 0.96f);
camViewPoint.y = Mathf.Clamp(camViewPoint.y, 0.07f, 0.93f);
//Convert to world point then apply result to the target object
Vector3 finalPos = Camera.main.ViewportToWorldPoint(camViewPoint);
targetRg.MovePosition(finalPos);
}