[英]C# Unity 2D Topdown Movement Script not working
I have been working on a unity project where the player controls a ship.我一直在做一个玩家控制一艘船的统一项目。 I was following along with a tutorial and have made an input script and a movement script that are tied together with unity's event system.
我跟着教程一起做了一个输入脚本和一个移动脚本,它们与统一的事件系统绑定在一起。 As far as I can tell my script and the script in the tutorial are the same, but the tutorial script functions and mine doesn't.
据我所知,我的脚本和教程中的脚本是一样的,但是教程脚本的功能和我的不一样。
Script to get player input获取玩家输入的脚本
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);
}
}
Script to move player移动玩家的脚本
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));
}
}
Any help would be appreciated!任何帮助,将不胜感激!
You need to attach your Handlers (HandleShooting and Handlemovement) to corresponding events.您需要将您的处理程序(HandleShooting 和 Handlemovement)附加到相应的事件。 Easiest way would be to make events static in PlayerInput
最简单的方法是在 PlayerInput 中制作事件 static
public static UnityEvent<Vector2> OnBoatMovement = new UnityEvent<Vector2>();
public static UnityEvent OnShoot = new UnityEvent();
and attach corresponding handlers to them in Movement.Awake并在 Movement.Awake 中为它们附加相应的处理程序
private void Awake(){
rb2d = GetComponent<Rigidbody2D>();
PlayerInput.OnBoatMovement += Handlemovement;
PlayerInput.OnShoot += HandleShooting;
}
Also in PlayerInput.BoatMovement you should probably check同样在 PlayerInput.BoatMovement 你应该检查
if(movementVector.sqrMagnitude > 0){
OnBoatMovement?.Invoke(movementVector.normalized);
}
Or else random shit may happen when trying to normalize Vector with magnitude 0 (I compare sqr magnitude to aviod calculating root which is never desired)否则,当尝试用幅度 0 归一化 Vector 时可能会发生随机问题(我将 sqr 幅度与 aviod 计算根进行比较,这是永远不需要的)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.