【问题标题】:C# Unity 2D Topdown Movement Script not workingC# Unity 2D 自上而下的运动脚本不起作用
【发布时间】:2021-12-23 05:01:09
【问题描述】:

我一直在做一个玩家控制一艘船的统一项目。我跟着教程一起做了一个输入脚本和一个移动脚本,它们与统一的事件系统绑定在一起。据我所知,我的脚本和教程中的脚本是一样的,但是教程脚本的功能和我的不一样。

获取玩家输入的脚本

    using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Events;

public class PlayerInput : MonoBehaviour
{
    
    public UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
    public UnityEvent OnShoot = new UnityEvent();


    void Update()
    {
        BoatMovement();
        Shoot();
    }

    private void Shoot()
    {
       if(Input.GetKey(KeyCode.F))
        {
            OnShoot?.Invoke();
        }
    }

    private void BoatMovement()
    {
        Vector2 movementVector = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        OnBoatMovement?.Invoke(movementVector.normalized);
    }
}

移动播放器的脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Movement : MonoBehaviour
{
    public Rigidbody2D rb2d;
    private Vector2 movementVector;
    public float maxspeed = 10;
    public float rotatespeed = 50;
    private void Awake()
    {
        rb2d = GetComponent<Rigidbody2D>();

    }
    public void HandleShooting()
    {
        Debug.Log("Shooting");
    }
    public void Handlemovement(Vector2 movementVector)
     {
        this.movementVector = movementVector;
     }
    private void FixedUpdate()
    {
        rb2d.velocity = (Vector2)transform.up * movementVector.y * maxspeed * Time.deltaTime;
        rb2d.MoveRotation(transform.rotation * Quaternion.Euler(0, 0, -movementVector.x * rotatespeed * Time.fixedDeltaTime));
    }
}    

任何帮助将不胜感激!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您需要将您的处理程序(HandleShooting 和 Handlemovement)附加到相应的事件。最简单的方法是在 PlayerInput 中将事件设为静态

    public static UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
    public static UnityEvent OnShoot = new UnityEvent();
    

    并在 Movement.Awake 中为它们附加相应的处理程序

    private void Awake(){
        rb2d = GetComponent<Rigidbody2D>();
        PlayerInput.OnBoatMovement += Handlemovement;
        PlayerInput.OnShoot += HandleShooting;
    }
    

    你也应该在 PlayerInput.BoatMovement 中检查

    if(movementVector.sqrMagnitude > 0){
        OnBoatMovement?.Invoke(movementVector.normalized);
    }
    

    否则,在尝试对幅度为 0 的向量进行归一化时可能会发生随机问题(我将 sqr 幅度与 aviod 计算根进行比较,这是永远不需要的)

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 2015-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多