Сверху вниз пуля не совсем точная
Я проверил через Youtube, Google и предыдущие ответы, но не могу заставить мою игру стрелять в сторону мыши. Игрок поворачивается, чтобы следовать за мышью, и когда он стреляет, он либо неточный, либо иногда стреляет в другом направлении. Я действительно не хочу отправлять огромное количество кода, но чувствую, что я смешал код из разных учебных пособий, возможно, было бы лучше, чтобы вы его увидели, хотя я вроде организовал его, так что извините, и заранее спасибо
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public int playerId = 0;
public bool useController;
public float Curserspeed = 5f;
public Animator animator;
public float speed;
public GameObject crossHair;
public GameObject bulletPrefab;
private Vector2 moveVelocity;
Vector3 movement;
Vector3 aim;
bool isAiming;
bool endOfAiming;
void Start()
{
}
// Update is called once per frame
void Update()
{
ProcessInputs();
AimAndShoot();
Animate();
Move();
Vector2 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Curserspeed* Time.deltaTime);
}
private void ProcessInputs() {
if (useController) {
movement = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0.0f);
aim = new Vector3(Input.GetAxisRaw("MoveHorizontal"), Input.GetAxisRaw("MoveVertical"), 0.0f);
aim.Normalize();
isAiming = Input.GetButton("Fire1");
endOfAiming = Input.GetButtonUp("fire1");
}
else {
movement = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"), 0.0f);
Vector3 mouseMovement = new Vector3(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"), 0.0f);
aim = aim + mouseMovement;
if (aim.magnitude > 0f)
{
aim.Normalize();
}
isAiming = Input.GetButton("Fire1");
endOfAiming = Input.GetButtonUp("Fire1");
}
if (movement.magnitude > 1.0f)
{
movement.Normalize();
}
}
private void Move()
{
transform.position = transform.position + movement * speed * Time.deltaTime;
}
private void Animate()
{
animator.SetFloat("vmovement", Input.GetAxisRaw("Horizontal"));
animator.SetFloat("movement", Input.GetAxisRaw("Vertical"));
animator.SetFloat("magnitude", movement.magnitude);
}
private void AimAndShoot()
{
Vector2 shootingDirection = new Vector2(aim.x, aim.y);
if (aim.magnitude > 0.0f)
shootingDirection.Normalize();
if (Input.GetButtonDown("Fire1")) {
GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
bullet.GetComponent<Rigidbody2D>().velocity = shootingDirection * 3.0f;
bullet.transform.Rotate(0.0f, 0.0f, Mathf.Atan2(shootingDirection.y, shootingDirection.x) * Mathf.Rad2Deg);
Destroy(bullet, 3.0f);
}
int main()
{
return 0;
}
`
1 ответ
Если ваш игрок смотрит на мышь, и вы пытаетесь стрелять там, это кажется немного сложным...
вам нужно сделать две вещи только после того, как вы создадите свою пулю: немедленно поверните ее, чтобы она смотрела в том же направлении, что и игрок. (это можно сделать с помощью transform.rotation= playerobject.rotation) применить силу вперед. (поскольку объект направлен туда, где находился ваш игрок, и поэтому прицеливается, когда вы "стреляли" снарядом, вам не нужно целиться, просто отправьте его по траектории движения вперед)
transform.forward
будет работать здесь.