【发布时间】:2014-05-29 22:50:35
【问题描述】:
嗨,溢出者们! 我最近深入研究了 Unity 中的 C#,因为我相信它比 UnityScript 具有更多功能,而且我来自 C++ 背景。从示例资产中的 2D 脚本中引用一些代码,我尝试创建自己的代码。代码如下:
using UnityEngine;
public class PlayerControl : MonoBehaviour {
//Variables
[HideInInspector]
public bool facingForward = true; //for Flip() Function
bool isGround = true; //for Grounded() Function
public float maxSpeed = 5.0f; //Terminal sideways velocity
public float HorizonAxis; //Checks for a/d movement
public float jumpFloat = 1000.0f; //Modular, use Unity Editor
public float moveFloat = 400.0f; // " "
void Start() {
//transform.position(0,0,0);
}
void Flip() {
facingForward = !facingForward; //switches boolean
Vector3 theScale = transform.localScale; //assigns vector to localscale of Player
theScale.x *= -1; //if x = 1, position becomes -1 and thus flips
transform.localScale = theScale; //reassigns the localscale to update theScale
}
bool Grounded() {
if (transform.position.y > 1) { //if position of gameObject is greater that 1, not grounded
isGround = false;
} else {
isGround = true;
}
return isGround; //function returns true or false for isGround
}
void Update() {
HorizonAxis = /*UnityEngine.*/Input.GetAxis ("Horizontal"); //assigns HorizonAxis to a/d movement from UnityEngine.Input
if (HorizonAxis * rigidbody2D.velocity.x > maxSpeed) { // if Input a/d by current x velocity of gameObject is greater than maxSpeed
rigidbody2D.velocity = new Vector2 (Mathf.Sign (rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y); //1 or -1 times the max speed, depending on direction
}
else if (HorizonAxis * rigidbody2D.velocity.x < maxSpeed) { //if Input a/d is less than terminal velocity
rigidbody2D.AddForce(Vector2.right * HorizonAxis * moveFloat); //add force to the right equivilant to Input by scalar moveFloat
}
if (Input.GetButtonDown ("Jump")) { //If Space
if(isGround) { //and isGround returns true
rigidbody2D.AddForce(new Vector2(0.0f, jumpFloat)); //add upwards force to bottom of rigidbody2D
isGround = false; //Resets isGround value
}
}
if (HorizonAxis > 0 && !facingForward) {//if UnityEngine.Input is to the right and facing left
Flip (); //execute
}
else if (HorizonAxis < 0 && facingForward) { //else
Flip (); //execute
}
}
}
不幸的是,代码不起作用。我没有编译错误,但任何输入都不会影响字符的当前位置。我应该使用 transform.Translate 来改变位置,还是坚持使用 AddForce 到 Vector2 直到角色达到 maxSpeed?
谢谢大家:)
【问题讨论】:
-
您是否尝试过使用 MonoDevelop 单步执行代码?
-
你的脚本适合我。是否有其他原因导致它无法移动?
-
我实际上注意到播放器和脚本之间存在链接错误,我已解决。我现在遇到的问题是控件真的很生涩,而且运行不顺畅,有什么建议吗?
-
在处理刚体和力时,应该使用 FixedUpdate() 而不是 Update()。在此处查看 Unity 描述:docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
-
这对左右移动有很大帮助。我遇到的问题是当角色在半空中时,我不能对他施加压力(x 轴运动不符合 y 轴),而且我不能让他保持直立:(跨度>
标签: c# unity3d 2d game-physics