c# - 我怎样才能让我的预制件从它的生成点完全反转(180 度)?统一二维
问题描述
所以我做了一个小侧滚轴,它使用预制件来产生子弹。我的问题是它只向一侧射击……右边。
我也需要它向左开火。我已经制作了一个变量来查看玩家是向右还是向左看。
我尝试将速度设置为 -20,并尝试将其在 Z 轴上旋转 180 度。我测试了子弹脚本是否甚至从玩家移动脚本中获取了更改,并且确实如此。
玩家移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public GameObject bullet;
private Rigidbody2D myRigidbody;
private float speed = 15;
private bool facingRight;
private bool ground = false;
private float jump = 23;
// Start is called before the first frame update
void Start()
{
facingRight = true;
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
Movement(horizontal);
Flip(horizontal);
if (Input.GetKey("w"))
{
if (ground)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, jump);
}
}
if(facingRight == false)
{
bullet.GetComponent<bullet>().left = true;
}
if (facingRight == true)
{
bullet.GetComponent<bullet>().left = false;
}
}
void OnTriggerEnter2D()
{
ground = true;
}
void OnTriggerExit2D()
{
ground = false;
}
private void Movement(float horizontal)
{
myRigidbody.velocity = new Vector2(horizontal * speed,myRigidbody.velocity.y);
}
private void Flip(float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal < 0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
}
武器脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weapon : MonoBehaviour
{
// Start is called before the first frame update
public bool right;
public Transform firepointR;
public GameObject bulletPrefab;
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
Debug.Log("Oh well");
Shoot();
}
}
void Shoot()
{
Instantiate(bulletPrefab, firepointR.position, firepointR.rotation);
}
}
项目符号脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour
{
public bool left;
public float speed = 20;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
// Update is called once per frame
void FixedUpdate()
{
Debug.Log(speed);
if (left == false)
{
transform.Rotate(0, 0, 180);
}
}
}
正如我之前所说,我需要我的子弹(预制件)向相反的方向前进,但无论我现在做什么,它总是会正确。
解决方案
扩展我的评论:
你试过反转速度吗?
rb.velocity = -(transform.right * speed);
注意:在某些情况下,使用负浮点数不会返回与正数相反的结果。但是,在此示例中,它可以正常工作。
我想这也会起作用(并且可能是正确的做法):
rb.velocity = transform.left * speed;
推荐阅读
- java - 仅通过可运行的 jar 在使用 java 的 pdf 加密期间出现错误,但使用 eclipse
- python - Kivy:所有屏幕上的导航栏
- php - Woo-com Rest api 订单更新不起作用
- r - 嵌套应用连接
- metadata - InnoDB 何时以及如何访问其元数据或索引?
- python - 关于合并图像的python和opencv的问题
- jetbrains-ide - 今天在我昨天运行的应用程序上出现新错误。意外的错误
- qt - 为什么在这个程序中接收数据丢失(使用QSerialPort)?
- docker - Sublime:打开从 docker 容器中触发异常的文件?
- python-3.x - 对大于和小于运算符感到困惑