Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

using UnityEngine; using UnityEditor; using UnityEngine.UI; using…

  1. User

    using UnityEngine; using UnityEditor; using UnityEngine.UI; using UnityEngine.EventSystems;

    public class PlayerMoveCode : GenericBehaviour { public float walkSpeed = 0.15f;
    public float runSpeed = 1.0f;
    public float sprintSpeed = 2.0f;
    public float speedDampTime = 0.1f;
    public float jumpHeight = 1.5f;
    public float jumpIntertialForce = 10f;
    private float speed, speedSeeker;
    private int jumpBool;
    private int groundedBool;
    private bool jump;
    private bool isColliding;
    public bool isLock;

    void Start()
    {
    	jumpBool = Animator.StringToHash("Jump");
    	groundedBool = Animator.StringToHash("Grounded");
    	behaviourManager.GetAnim.SetBool(groundedBool, true);
    
    	behaviourManager.SubscribeBehaviour(this);
    	behaviourManager.RegisterDefaultBehaviour(this.behaviourCode);
    	speedSeeker = runSpeed;
    
    	//Hide mouse
    	Time.timeScale = 1;
    	//Cursor.lockState = CursorLockMode.Locked;
    	//Cursor.visible = false;
    }
    
    void Update()
    {
    	if (!jump && Input.GetKeyDown(KeyCode.Space) && behaviourManager.IsCurrentBehaviour(this.behaviourCode) && !behaviourManager.IsOverriding())
    	{
    		jump = true;
    	}
    
    
    	//Press ESC pause
    	//if (Input.GetKeyDown(KeyCode.Escape))
    	//{
    	//	isLock = !isLock;
    	//	if (isLock)
    	//	{
    	//		Time.timeScale = 0;
    	//		Cursor.lockState = CursorLockMode.None;
    	//		Cursor.visible = true;
    	//	}
    	//	else
    	//	{
    	//		Time.timeScale = 1;
    	//		Cursor.lockState = CursorLockMode.Locked;
    	//		Cursor.visible = false;
    	//	}
    	//}
    }
    
    
    public override void LocalFixedUpdate()
    {
    	MovementManagement(behaviourManager.GetH, behaviourManager.GetV);
    
    
    	JumpManagement();
    }
    
    
    void JumpManagement()
    {
    	if (jump && !behaviourManager.GetAnim.GetBool(jumpBool) && behaviourManager.IsGrounded())
    	{
    		behaviourManager.LockTempBehaviour(this.behaviourCode);
    		behaviourManager.GetAnim.SetBool(jumpBool, true);
    
    		if (behaviourManager.GetAnim.GetFloat(speedFloat) > 0.1)
    		{
    
    			GetComponent<CapsuleCollider>().material.dynamicFriction = 0f;
    			GetComponent<CapsuleCollider>().material.staticFriction = 0f;
    
    			RemoveVerticalVelocity();
    
    			float velocity = 2f * Mathf.Abs(Physics.gravity.y) * jumpHeight;
    			velocity = Mathf.Sqrt(velocity);
    			behaviourManager.GetRigidBody.AddForce(Vector3.up * velocity, ForceMode.VelocityChange);
    		}
    	}
    
    	else if (behaviourManager.GetAnim.GetBool(jumpBool))
    	{
    		if (!behaviourManager.IsGrounded() && !isColliding && behaviourManager.GetTempLockStatus())
    		{
    			behaviourManager.GetRigidBody.AddForce(transform.forward * jumpIntertialForce * Physics.gravity.magnitude * sprintSpeed, ForceMode.Acceleration);
    		}
    
    		if ((behaviourManager.GetRigidBody.velocity.y < 0) && behaviourManager.IsGrounded())
    		{
    			behaviourManager.GetAnim.SetBool(groundedBool, true);
    
    			GetComponent<CapsuleCollider>().material.dynamicFriction = 0.6f;
    			GetComponent<CapsuleCollider>().material.staticFriction = 0.6f;
    
    			jump = false;
    			behaviourManager.GetAnim.SetBool(jumpBool, false);
    			behaviourManager.UnlockTempBehaviour(this.behaviourCode);
    		}
    	}
    }
    
    
    void MovementManagement(float horizontal, float vertical)
    {
    	if (behaviourManager.IsGrounded())
    		behaviourManager.GetRigidBody.useGravity = true;
    
    
    	else if (!behaviourManager.GetAnim.GetBool(jumpBool) && behaviourManager.GetRigidBody.velocity.y > 0)
    	{
    		RemoveVerticalVelocity();
    	}
    
    	Rotating(horizontal, vertical);
    
    
    	Vector2 dir = new Vector2(horizontal, vertical);
    	speed = Vector2.ClampMagnitude(dir, 1f).magnitude;
    
    	speedSeeker += Input.GetAxis("Mouse ScrollWheel");
    	speedSeeker = Mathf.Clamp(speedSeeker, walkSpeed, runSpeed);
    	speed *= speedSeeker;
    	if (behaviourManager.IsSprinting())
    	{
    		speed = sprintSpeed;
    	}
    
    	behaviourManager.GetAnim.SetFloat(speedFloat, speed, speedDampTime, Time.deltaTime);
    }
    
    
    private void RemoveVerticalVelocity()
    {
    	Vector3 horizontalVelocity = behaviourManager.GetRigidBody.velocity;
    	horizontalVelocity.y = 0;
    	behaviourManager.GetRigidBody.velocity = horizontalVelocity;
    }
    
    Vector3 Rotating(float horizontal, float vertical)
    {
    	Vector3 forward = behaviourManager.playerCamera.TransformDirection(Vector3.forward);
    
    	forward.y = 0.0f;
    	forward = forward.normalized;
    
    	Vector3 right = new Vector3(forward.z, 0, -forward.x);
    	Vector3 targetDirection;
    	targetDirection = forward * vertical + right * horizontal;
    
    	if ((behaviourManager.IsMoving() && targetDirection != Vector3.zero))
    	{
    		Quaternion targetRotation = Quaternion.LookRotation(targetDirection);
    
    		Quaternion newRotation = Quaternion.Slerp(behaviourManager.GetRigidBody.rotation, targetRotation, behaviourManager.turnSmoothing);
    		behaviourManager.GetRigidBody.MoveRotation(newRotation);
    		behaviourManager.SetLastDirection(targetDirection);
    	}
    	if (!(Mathf.Abs(horizontal) > 0.9 || Mathf.Abs(vertical) > 0.9))
    	{
    		behaviourManager.Repositioning();
    	}
    
    	return targetDirection;
    }
    
    
    private void OnCollisionStay(Collision collision)
    {
    	isColliding = true;
    	if (behaviourManager.IsCurrentBehaviour(this.GetBehaviourCode()) && collision.GetContact(0).normal.y <= 0.1f)
    	{
    		GetComponent<CapsuleCollider>().material.dynamicFriction = 0f;
    		GetComponent<CapsuleCollider>().material.staticFriction = 0f;
    	}
    }
    private void OnCollisionExit(Collision collision)
    {
    	isColliding = false;
    	GetComponent<CapsuleCollider>().material.dynamicFriction = 0.6f;
    	GetComponent<CapsuleCollider>().material.staticFriction = 0.6f;
    }
    

    }在不改变该代码的基础上,添加一个上楼代码按Q键上楼,楼梯每节高20cm,台阶每个32cm,按住Q键连续上楼,按住E键是下楼,一定不能改变原代码的功能,并用中文详细注释

  2. Assistant

    要实现这个功能,我们需要在 PlayerMoveCode 类中添加相应的成员变量和方法来支持上楼和下楼功能。

    首先定义相关的变量:

    public float stepUpHeight = 0.2f; //楼梯每节高20cm
    public float stepDistance = 0.32f; //台阶每个32cm
    private bool isClimbing = false; // 是否正在上楼或下楼
    private KeyCode climbUpKey = KeyCode.Q; // 上楼键
    private KeyCode climbDownKey = KeyCode.E; // 下楼键
    

    然后在 Update() 方法中处理按键输入:

    void Update()
    {
        // 省略已有代码 ...
        
        if (Input.GetKey(climbUpKey) && !isClimbing)
        {
            StartCoroutine(ClimbStep(new Vector3(0, stepUpHeight, stepDistance)));
        }
        
        if (Input.GetKey(climbDownKey) && !isClimbing)
        {
            StartCoroutine(ClimbStep(new Vector3(0, -stepUpHeight, -stepDistance)));
        }
    }
    

    在这里,我们使用 Coroutine(协程)来实现按住键连续上楼和下楼的效果。

    接着实现 ClimbStep 方法:

    IEnumerator ClimbStep(Vector3 targetOffset)
    {
        isClimbing = true;
        
        // 获取移动目标点
        Vector3 targetPosition = transform.position + transform.TransformDirection(targetOffset);
        
        // 在当前位置和目标位置之间创建一个BoxCast检查是否有障碍物
        RaycastHit hit;
        bool hasObstacle = Physics.BoxCast(transform.position, GetComponent<CapsuleCollider>().size / 2, targetOffset.normalized, out hit, transform.rotation, targetOffset.magnitude);
        
        if (!hasObstacle)
        {
            // 创建一个循环使玩家移动到目标位置
            float startTime = Time.time;
            float journeyLength = Vector3.Distance(transform.position, targetPosition);
            float speed = journeyLength / 0.2f; // 每次移动的时间为0.2秒
            
            while (Vector3.Distance(transform.position, targetPosition) > 0.001f)
            {
                float distCovered = (Time.time - startTime) * speed;
                float fractionOfJourney = distCovered / journeyLength;
                transform.position = Vector3.Lerp(transform.position, targetPosition, fractionOfJourney);
                yield return null;
            }
            
            // 将位置设置为目标位置,以防移动过程中出现误差
            transform.position = targetPosition;
        }
        
        isClimbing = false;
    }
    

    这个方法使用了协程(Coroutine),在按下上楼键或下楼键时平滑地移动玩家位置。使用 BoxCast 检测玩家前方是否有障碍物来避免穿越墙壁。

    最后,在 LocalFixedUpdate() 方法中根据 isClimbing 的状态来处理 Jump 跳跃和 Move 移动逻辑:

    public override void LocalFixedUpdate()
    {
        if (!isClimbing)
        {
            MovementManagement(behaviourManager.GetH, behaviourManager.GetV);
            JumpManagement();
        }
    }
    

    现在代码已经实现了按住 Q 键连续上楼、按住 E 键连续下楼的功能,且不影响原本代码的其他功能。其中包括 Q 和 E 键的检测、玩家位置的平滑移动以及碰撞检测避免穿越墙壁。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.