[英]C# Unity 2D Topdown Movement Script not working
我一直在做一個玩家控制一艘船的統一項目。 我跟着教程一起做了一個輸入腳本和一個移動腳本,它們與統一的事件系統綁定在一起。 據我所知,我的腳本和教程中的腳本是一樣的,但是教程腳本的功能和我的不一樣。
獲取玩家輸入的腳本
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));
}
}
任何幫助,將不勝感激!
您需要將您的處理程序(HandleShooting 和 Handlemovement)附加到相應的事件。 最簡單的方法是在 PlayerInput 中制作事件 static
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 歸一化 Vector 時可能會發生隨機問題(我將 sqr 幅度與 aviod 計算根進行比較,這是永遠不需要的)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.