【发布时间】:2019-12-21 15:16:39
【问题描述】:
所以在 Unity 中我的盒子碰撞存在问题,当我的角色从顶部或底部与盒子碰撞时,它可以正常工作并停止,但是当它从左侧或右侧向它移动时它会不要停下来,这不是我想要发生的。如果有人能告诉我我做错了什么,那就太好了。 (统一2019.2.12f1)
角色的框碰撞
平台的框碰撞
public class playermovement : MonoBehaviour
{
public float spelerspeed = 8.0f;
public float top = 276.0f;
public float bottom = -270.0f;
public bool isgrounded = false;
public bool iswall = false;
public int var = 0;
public float jumpheight = 11500f;
public float Djumpheight = 11500f;
private Rigidbody2D rigidbody;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
userinput();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "ground")
{
isgrounded = true;
var = 0;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.collider.tag == "ground")
{
isgrounded = false;
var = 1;
}
}void userinput()
{
if (Input.GetKeyDown(KeyCode.Space) && var == 1)
{
Rigidbody2D rb2d = gameObject.GetComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(rb2d.velocity.x, 0);
rb2d.AddForce(Vector2.up, ForceMode2D.Impulse);
var = 2;
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, Djumpheight), ForceMode2D.Impulse);
}
if (Input.GetKeyDown(KeyCode.Space) && isgrounded == true)
{
var = 1;
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpheight), ForceMode2D.Impulse);
}
if (transform.localPosition.x >= top)
{
transform.localPosition = new Vector3(-269, -83,0);
}
if (transform.localPosition.x <= bottom)
{
transform.localPosition = new Vector3(275, -83, 0);
}
if (Input.GetKey(KeyCode.A)|| Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.D) == false)
{
if (Input.GetKey(KeyCode.D))
{
}
else
{
transform.localRotation = Quaternion.Euler(0, 180, 0);
}
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)&& Input.GetKey(KeyCode.A) == false)
{
if (Input.GetKey(KeyCode.A))
{
}
else
{
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.localPosition += move * spelerspeed * Time.deltaTime;
}
}
【问题讨论】:
-
只是另一个问题/旁注:为什么如果在
Start中你已经在userInput中分配了rigidbody,你又在rb2d中再次分配,然后直接在gameObject.GetComponent ...中分配一次......简单在任何地方都使用rigidbody,这样会更有效率;) -
如果没有与地面发生碰撞,则没有代码可以执行任何操作...
-
也是一个字段/变量名
var不好...var是一个关键字。userInput中没有任何内容以不同方式处理var == 0案例 -
当学习是最糟糕的事情时养成坏习惯,打破一个长期存在的习惯比不这样做更难
标签: c# unity3d rigid-bodies