Unity 之 上下左右键控制物体移动(通过加速度、速度进行移动)

[Range(0,0.2f)]
public float speed = 0.5f;

Vector3 velocity = Vector3.zero;
Vector3 accel = Vector3.zero;

if (Input.GetKey(KeyCode.RightArrow)) {
     accel = Vector3.right * speed;
} else if (Input.GetKey(KeyCode.LeftArrow)) {
     accel = Vector3.left * speed;
} else if (Input.GetKey(KeyCode.UpArrow)) {
     accel = Vector3.forward * speed;
} else if (Input.GetKey(KeyCode.DownArrow)) {
     accel = Vector3.back * speed;
} else {
     accel = Vector3.zero;
}

velocity += accel;
velocity *= 0.95f;
transform.localPosition += velocity;
if (transform.localPosition.x > right) {
     transform.localPosition = new Vector3(right, transform.localPosition.y, transform.localPosition.z);
     accel *= -1;
}
if (transform.localPosition.x < left) {
     transform.localPosition = new Vector3(left, transform.localPosition.y, transform.localPosition.z);
     accel *= -1;
}
if (transform.localPosition.z > back) {
     transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, back);
     accel *= -1;
}
if (transform.localPosition.z < front) {
     transform.localPosition = new Vector3(transform.localPosition.x, transform.localPosition.y, front);
     accel *= -1;
}

以上代码来自【Liquid Volume】插件

 

你可能感兴趣的:(Unity 之 上下左右键控制物体移动(通过加速度、速度进行移动))