我正在尝试制作一个2d平台,您可以从侧面看到玩家。我希望他不断前进,您必须在正确的时间按空格,以免他跌倒。现在一切正常,但他没有与地面碰撞。我希望它就像他在墙后奔跑一样,所以我想忽略我已完成的某个图层并与下面的框碰撞。到目前为止,我已经尝试了射线投射,观看了多个教程,并且进行了盒碰撞。盒式碰撞虽然有效,但要使所有平台都算是可靠的,我需要50个盒式对撞机。这是我当前的代码:
public int playerSpeed = 10;
public int playerJumpPower = 1250;
public float moveX;
public float playerYSize = 2;
public LayerMask mainGround;
public float playerFallSpeed = 5;
void Awake(){
}
// Update is called once per frame
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, new Vector2(10, 0));
if(hit.distance < 0.7f){
print("hi");
}
Vector3 characterTargetPosition = new Vector3(transform.position.x + playerSpeed, transform.position.y, transform.position.z);
transform.position = Vector3.Lerp(transform.position, characterTargetPosition, playerSpeed * Time.deltaTime);
if(Input.GetKeyDown("space")){
// float playerTargetPosY = transform.position.y + playerJumpPower;
// Vector3 characterTargetPosition = new Vector3(transform.position.x, playerTargetPosY, transform.position.z);
// transform.position = Vector3.Lerp(transform.position, characterTargetPosition, playerJumpPower * Time.deltaTime);
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector2.up * playerJumpPower);
}
//PlayerMove();
}
我的播放器上有一个苯乙烯模型2D,所以现在他只是跌倒在地,但跳跃确实起作用。如果有任何简单的方法可以做到这一点。像一些脚本,教程或网站一样,我也欢迎您。请帮忙。
答案 0 :(得分:1)
您的播放器中是否有Rigidbody2D?要移动的东西通常必须具有RigidBody
(很抱歉,将其发布为答案。还不能发表评论)
编辑:
尝试一下:
Rigidbody2D rb;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
//Physics usually are done in FixedUpdate to be more constant
public void FixedUpdate(){
if (Input.GetKeyDown("space"))
{
if(!rb.simulated)
//player can fall
rb.simulated = true;
rb.AddForce(Vector2.up * playerJumpPower);
}
else
{
//third argument is the distance from the center of the object where it will collide
//therefore you want the distance from the center to the bottom of the sprite
//which is half of the player height if the center is acctually in the center of the sprite
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, playerYSize / 2);
if (hit.collider)
{
//make player stop falling
rb.simulated = false;
}
}
}
如果玩家是唯一会与某物体发生碰撞的物体,则只需从该玩家不会与之碰撞的物体中取出碰撞器即可。
否则,您可以使用hit.collider.gameObject.layer
检查碰撞对象的层,并确定玩家是否会与该层碰撞
(请注意,您必须与图层的索引进行比较。如果要通过索引的名称获取索引,可以使用LayerMask.NameToLayer(/*layer name*/)
)
每次要使用RigidBody(例如AddForce())做某事时,您都必须做rb.simulated = true
希望它有帮助:)