最近,我为2D游戏实现了射击系统,但是该系统存在问题.问题在于,当玩家面对左侧时,子弹仍在向右射击.要解决此问题,我需要访问
Vector2
名为
targetVelocity
检查播放器是否正确.
targetVelocity
在另一个脚本中定义,称为
PhysicsObject
专门用于播放器物理,并且播放器脚本从中继承(变量为
protected
但我将其更改为
public
).我只是不知道该如何在我的
Bullet
中引用
脚本,而我不想将播放器脚本添加到项目符号中.另外,我已经阅读了与之相似的过去的问题和答案,但是由于情况不同,我还没有找到答案.预先感谢。
This is my
Bullet
脚本,我想以某种方式引用
targetVelocity
。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] float lifeTime;
public GameObject destroyEffect;
private void Start()
{
Invoke("DestroyBullet", lifeTime);
}
private void Update()
{
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
void DestroyBullet()
{
Instantiate(destroyEffect, transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
Here is the weapon script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public GameObject bullet;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
private void Update()
{
if (timeBtwShots <= 0)
{
if (Input.GetButton("Fire1"))
{
Instantiate(bullet, firePoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
This is the player script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewPlayer : PhysicsObject
{
[Header("Attributes")]
[SerializeField] private float jumpPower = 10;
[SerializeField] private float maxSpeed = 1;
//Singleton instantation
private static NewPlayer instance;
public static NewPlayer Instance
{
get
{
if (instance == null) instance = GameObject.FindObjectOfType<NewPlayer>();
return instance;
}
}
// Update is called once per frame
void Update()
{
targetVelocity = new Vector2(Input.GetAxis("Horizontal") * maxSpeed, 0);
//If the player presses "Jump" and we're grounded, set the velocity to a jump power value
if (Input.GetButtonDown("Jump") && grounded)
{
velocity.y = jumpPower;
}
//Flip the player's localScale.x if the move speed is greater than .01 or less than -.01
if (targetVelocity.x < -.01)
{
transform.localScale = new Vector2(-1, 1);
}
else if (targetVelocity.x > .01)
{
transform.localScale = new Vector2(1, 1);
}
}
}
最新回答
- 2021-1-21 #
对项目符号的简单解决方法是抓住开始创建项目符号的方向,然后以这种方式飞行.可能会有更优雅的解决方案,并且对targetVelocity的引用似乎很奇怪,但这就是您要的。