在我的游戏中,我有一个开关。开关上有一个触发器,用于检测播放器何时触摸,这样他/她可以按下'E'轻弹它。
奇怪的部分是我只能在玩家移动时触发开关,我使用addforce进行移动。
以下是我的播放器和我的开关的代码。我还附上了我的项目文件夹,以便如果有人愿意花时间尝试,他们可以。对我来说,复制率是100%的时间。
显然这不是预期的结果,玩家应该能够激活开关,即使它们静止不动。
PLAYERMOVEMENT.CS:
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
private Rigidbody2D R2Dplayer;
private bool grounded = true;
[SerializeField] private Animator anim;
// Use this for initialization
void Start () {
R2Dplayer = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
anim.SetFloat("speed", Mathf.Abs(R2Dplayer.velocity.x));
if(Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.Space)) {
if(grounded == true) {
R2Dplayer.AddForce (new Vector2(0,7.5f), ForceMode2D.Impulse);
}
}
if(Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
R2Dplayer.AddForce (new Vector2(-0.2f,0), ForceMode2D.Impulse);
if (R2Dplayer.transform.rotation == new Quaternion (0.0f, 0.0f, 0.0f, 1.0f)) {
R2Dplayer.transform.Rotate (0, 180, 0);
}
}
if(Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) {
}
if(Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
R2Dplayer.AddForce (new Vector2(0.2f,0), ForceMode2D.Impulse);
if (R2Dplayer.transform.rotation == new Quaternion (0.0f, -1.0f, 0.0f, 0.0f)) {
R2Dplayer.transform.Rotate (0, 180, 0);
}
}
}
void OnTriggerEnter2D(Collider2D c) {
if(c.tag == "JumpTrigger") {
grounded = true;
}
}
void OnTriggerExit2D(Collider2D c) {
if(c.tag == "JumpTrigger") {
grounded = false;
}
}
}
SWITCH.CS:
using UnityEngine;
using System.Collections;
public class Switch : MonoBehaviour {
[SerializeField] public bool switchPressed = false;
private SpriteRenderer sr;
[SerializeField] private Sprite on, off;
// Use this for initialization
void Start () {
sr = GetComponent<SpriteRenderer> ();
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay2D(Collider2D c) {
if(c.tag == "Player") {
if(Input.GetKeyDown(KeyCode.E)) {
if(switchPressed == false) {
sr.sprite = on;
switchPressed = true;
}
else if(switchPressed == true) {
sr.sprite = off;
switchPressed = false;
}
}
}
}
}
我的项目的ZIP,可以从dropbox下载:https://www.dropbox.com/s/85anfa4287mciiy/Final.zip?dl=0