英文:
Unity - How can I fix this code so it works without transform.position = newPosition?
问题
以下是您提供的代码部分的中文翻译:
所以我的角色必须在塔周围走动,很简单。
但是,由于我愚蠢,只能在Update
中使用transform.position
来解决问题,所以跳跃和碰撞当然不起作用。
这是塔的概念(查看图像)塔
这是目前的工作方式(查看视频:https://streamable.com/7tmq1l)
在片段中,您会看到如果我注释掉transform.position = newPosition
以允许跳跃,它会如何破坏。
这是我使用的代码:
public class Movement : MonoBehaviour
{
[SerializeField] private float radius = 7;
[SerializeField] private float angleSpeed = 28;
[SerializeField] private float jumpForce = 5;
private float angle;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
transform.rotation = Quaternion.Euler(0, angle, 0);
float horizontalInput = Input.GetAxis("Horizontal");
angle -= horizontalInput * angleSpeed * Time.deltaTime;
Vector3 newPosition = Quaternion.Euler(0, angle, 0) * new Vector3(0, 0, radius);
transform.position = newPosition;
//跳跃
if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W))
{
Debug.Log("跳跃!");
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
当然,跳跃不起作用是因为这个。
英文:
so my character has to walk around a tower, simple
but me being stupid can only work it out by using transform.position in update so jumping and collisions ofc, dont work
here is the tower concept ( see image )
Tower
here is how it works rn (see video: https://streamable.com/7tmq1l)
You will see in the clip how bad it breaks if i comment the transform.position = newposition to allow for jumping
Here is my code I used:
public class Movement : MonoBehaviour
{
[SerializeField] private float radius = 7;
[SerializeField] private float angleSpeed = 28;
[SerializeField] private float jumpForce = 5;
private float angle;
Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
transform.rotation = Quaternion.Euler(0, angle, 0);
float horizontalInput = Input.GetAxis("Horizontal");
angle -= horizontalInput * angleSpeed * Time.deltaTime;
Vector3 newPosition = Quaternion.Euler(0, angle, 0) * new Vector3(0, 0, radius);
transform.position = newPosition;
//jump
if(Input.GetKeyDown(KeyCode.Space)|| Input.GetKeyDown(KeyCode.W))
{
Debug.Log("Jumping!");
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
Ofc the jumping doesnt work because of this
答案1
得分: 0
使用刚体(rigidBody)来调整XZ位置,并让刚体(rigidBody)调整Y轴。
Vector3 newPosition = Quaternion.Euler(0, angle, 0) * radius;
newPosition.Y = rb.position.Y; // 保持Y不变以允许跳跃
rb.position = newPosition;
英文:
adjust the XZ position using the rigidBody and let the rb adjust the Y axis.
Vector3 newPosition = Quaternion.Euler(0, angle, 0) * radius;
newPosition.Y = rb.position.Y; // leave Y unchanged to allow for jumps
rb.position = newPosition;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论