NerdyPegasus
NerdyPegasus
CC#
Created by NerdyPegasus on 5/7/2024 in #help
Cannon not following mouse?
Hello! I'm trying to have my cannon change position based on where the mouse is, but it always chooses to the same angle when the mouse is clicked no matter its placement on the screen. Does anyone know what is causing this? And what I need to fix and with what? C# in Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CannonManager : MonoBehaviour
{
public GameObject cannonBallPrefab;
public Transform firePoint;


private Camera _cam;
private bool _pressingMouse = false;

private Vector3 _initialVelocity;

void Start()
{
_cam = Camera.main;
}

void Update()
{
if (Input.GetMouseButtonDown(0))
_pressingMouse = true;
if (Input.GetMouseButtonUp(0))
{
_pressingMouse = false;
_Fire();
}

if (_pressingMouse)
{
// coordinate transform screen > world
Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;

// look at
transform.LookAt(mousePos);
}
}

private void _Fire()
{
// instantiate a cannon ball
GameObject cannonBall = Instantiate(cannonBallPrefab, firePoint.position, Quaternion.identity);
// apply some force
Rigidbody rb = cannonBall.GetComponent<Rigidbody>();
rb.AddForce(_initialVelocity, ForceMode.Impulse);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CannonManager : MonoBehaviour
{
public GameObject cannonBallPrefab;
public Transform firePoint;


private Camera _cam;
private bool _pressingMouse = false;

private Vector3 _initialVelocity;

void Start()
{
_cam = Camera.main;
}

void Update()
{
if (Input.GetMouseButtonDown(0))
_pressingMouse = true;
if (Input.GetMouseButtonUp(0))
{
_pressingMouse = false;
_Fire();
}

if (_pressingMouse)
{
// coordinate transform screen > world
Vector3 mousePos = _cam.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;

// look at
transform.LookAt(mousePos);
}
}

private void _Fire()
{
// instantiate a cannon ball
GameObject cannonBall = Instantiate(cannonBallPrefab, firePoint.position, Quaternion.identity);
// apply some force
Rigidbody rb = cannonBall.GetComponent<Rigidbody>();
rb.AddForce(_initialVelocity, ForceMode.Impulse);
}
}
11 replies