Car GameObject falling through the Terrain - c#

I have been working on a project recently and there is a scene where there are mountains, forests and a car.
When the car moves on the terrain, the car penetrates through the terrain
I just want to know how to stop this from happening.
On the Car there is Mesh Collider and RigidBody is attached
On Terrain There is Mesh Collider with Convex to False.
public class Motor : MonoBehaviour {
public float moveSpeed = 5.0f;
public float drag = 0.5f;
public float terminalRoatationSpeed = 25.0f;
public Virtualjoystick moveJoystick;
private Rigidbody controller;
private Transform camTransform;
// Use this for initialization
void Start () {
controller = GetComponent<Rigidbody> ();
controller.maxAngularVelocity = terminalRoatationSpeed;
controller.drag = drag;
camTransform = Camera.main.transform;
}
// Update is called once per frame
void FixedUpdate () {
Vector3 dir = Vector3.zero;
dir.x = Input.GetAxis ("Horizontal");
dir.z = Input.GetAxis ("Vertical");
if(dir.magnitude > 1)dir.Normalize();
if(moveJoystick.InputDirection != Vector3.zero)
{
dir = moveJoystick.InputDirection;
}
// Rotate our Direction vector with Camera
Vector3 rotatedDir = camTransform.TransformDirection(dir);
rotatedDir = new Vector3 (rotatedDir.x, 0, rotatedDir.z);
rotatedDir = rotatedDir.normalized * dir.magnitude;
controller.AddForce (rotatedDir * moveSpeed);
}
}

I've answered this question before but can't find the other answer to mark this as a duplicate. You use WheelCollider for cars.
You need to attach WheelCollider to all the wheels of your car. By doing this your car will always be on top of the Terrain Collider.
WheelCollider.motorTorque is used to move the car forward or backwards.
WheelCollider.brakeTorque is used to brake the car.
WheelCollider.steerAngle is used to steer the car.
There are many tutorials out there and here is one example directly from Unity's doc:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleInfo {
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
public class SimpleCarController : MonoBehaviour {
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;
// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0) {
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
visualWheel.transform.rotation = rotation;
}
public void FixedUpdate()
{
float motor = maxMotorTorque * Input.GetAxis("Vertical");
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos) {
if (axleInfo.steering) {
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor) {
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
}

Related

My 3D racing game has some problems like wheels turning y axis and car not going anywhere

My car's tires spin but the car doesn't move an inch and the wheels turn into y axis instead of left and right. Here is my code, i added rigidbody and boxcollider onto my car aswell maybe that's a problem causing the car not to move? (i made sure to put the collider above the wheels to make sure that they spin.)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
private float horizontalInput;
private float verticalInput;
private float steerAngle;
private bool isBreaking;
public WheelCollider FrontLeftCollider;
public WheelCollider FrontRightCollider;
public WheelCollider BackLeftCollider;
public WheelCollider BackRightCollider;
public Transform FrontLeftTransform;
public Transform FrontRightTransform;
public Transform BackLeftTransform;
public Transform BackRightTransform;
public float maxSteeringAngle = 30f;
public float motorForce = 50f;
public float brakeForce = 0f;
private void FixedUpdate()
{
GetInput();
HandleMotor();
HandleSteering();
UpdateWheels();
}
private void GetInput()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
isBreaking = Input.GetKey(KeyCode.Space);
}
private void HandleSteering()
{
steerAngle = maxSteeringAngle * horizontalInput;
FrontLeftCollider.steerAngle = steerAngle;
FrontRightCollider.steerAngle = steerAngle;
}
private void HandleMotor()
{
FrontLeftCollider.motorTorque = verticalInput * motorForce;
FrontRightCollider.motorTorque = verticalInput * motorForce;
brakeForce = isBreaking ? 3000f : 0f;
FrontLeftCollider.brakeTorque = brakeForce;
FrontRightCollider.brakeTorque = brakeForce;
BackLeftCollider.brakeTorque = brakeForce;
BackRightCollider.brakeTorque = brakeForce;
}
private void UpdateWheels()
{
UpdateWheelPos(FrontLeftCollider, FrontLeftTransform);
UpdateWheelPos(FrontRightCollider, FrontRightTransform);
UpdateWheelPos(BackLeftCollider, BackLeftTransform);
UpdateWheelPos(BackRightCollider, BackRightTransform);
}
private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans)
{
Vector3 pos;
Quaternion rot;
wheelCollider.GetWorldPose(out pos, out rot);
trans.rotation = rot;
trans.position = pos;
}
}
If needed i can send screenshots of things please don't be shy to ask.
I haven't tried anything too afraid to make it worse
A rigidbody will not move until some kind of force is applied to it, or you use it's MovePosition method. Here is a link ... https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html

Hinge Joint 2d not working properly in my Unity script

I decided to move objects with the mouse. Everything worked out, but I decided to make everything more realistic and added Hingle Joint 2d
And it doesn’t work at all. If you disable ConnectedBody in the code, then the object will attach with its Achor in the wrong direction at all
Ps: I tried to change the value of Mouse to MouseTransofrm
CODE :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragItems : MonoBehavior
{
public Rigidbody2D selectedObject;
public HingeJoint2D StopCenter = null;
public Rigidbody2D obj;
public Vector2 Mouse;
public Transform Mousetransform;
Vector3 offset;
Vector3 mousePosition;
public float maxSpeed = 10;
Vector2 mouseForce;
Vector3 lastPosition;
void Update()
{
Mouse = Mousetransform.transform.position;
mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if (selectedObject)
{
mouseForce = (mousePosition - lastPosition) / Time.deltaTime;
mouseForce = Vector2.ClampMagnitude(mouseForce, maxSpeed);
lastPosition = mousePosition;
}
if (Input.GetMouseButtonDown(0))
{
Collider2D targetObject = Physics2D.OverlapPoint(mousePosition);
if (targetObject)
{
selectedObject = targetObject.transform.gameObject.GetComponent();
offset = selectedObject.transform.position - mousePosition;
}
}
if (Input.GetMouseButtonUp(0) && selectedObject)
{
selectedObject.velocity = Vector2.zero;
selectedObject.AddForce(mouseForce, ForceMode2D.Impulse);
selectedObject = null;
}
}
void FixedUpdate()
{
if (selectedObject)
{
selectedObject.MovePosition(mousePosition + offset);
StopCenter = selectedObject.GetComponent();
StopCenter.enabled = true;
StopCenter.connectedBody = obj;
StopCenter.anchor = Mouse;
}
}
}

How to change hit point to crosshair?

Below script uses a function whereas there first is a check if there is a object in range and if it, it is.
On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to
always being able to fire (indifferent if the object is in range) and
shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.
I am a novice at coding and I can't see what code to remove and what to add.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
public struct ShootHit
{
public GameObject gameObject;
public Vector3 point;
}
[System.Serializable]
public class UnityEventShootHit : UnityEvent<ShootHit> { }
[DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
public class ShootComponent : MonoBehaviour
{
[Header("Input")]
[Tooltip("Data that determines the input of player actions")]
[SerializeField] private InputProfile _inputProfile;
// [SerializeField] private float _range = 100.0f;
/* [Header("Sight Values")]
[Tooltip("How far the the sight can reach")]
public float sightRadius = 1f;
[Range(0f, 360f)]
public float fieldOfViewAngle = 100f;*/
[Header("Charge-up")]
[SerializeField] private float _chargeupTime = 0.5f;
private bool _isChargingPrimary = false;
private bool _isChargingSecondary = false;
[Header("Aim Assist")]
[SerializeField] private LayerMask _aimAssistLayerMask;
public float aimAssistRadius = 30.0f; // radius
[Range(0.0f, 360.0f)]
public float aimAssistMaxAngleToAssist = 45.0f; // angle
private ShootHit? _target;
//publics
public Transform shootOrigin;
[Header("Events")]
public UnityEventShootHit OnPrimaryFire;
public UnityEvent OnPrimaryFireStart;
public UnityEvent OnPrimaryFireStop;
public UnityEventShootHit OnSecondaryFire;
public UnityEvent OnSecondaryFireStart;
public UnityEvent OnSecondaryFireStop;
private void Start()
{
if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
have a player input");
}
private void Update()
{
// Remove target if object is too far away
if (_target.HasValue)
{
if (Vector3.Distance(_target.Value.gameObject.transform.position,
transform.position) > aimAssistRadius)
{
_target = null;
}
}
if (_inputProfile.GetPrimaryFireButtonDown())
{
StopCoroutine(ChargeUpBeforeFireSecondary());
if (!_isChargingPrimary)
{
StartCoroutine(ChargeUpBeforeFirePrimary());
}
}
else if (_inputProfile.GetSecondaryFireButtonDown())
{
StopCoroutine(ChargeUpBeforeFirePrimary());
if (!_isChargingSecondary)
{
StartCoroutine(ChargeUpBeforeFireSecondary());
}
}
if (_inputProfile.GetPrimaryFireButton() ||
_inputProfile.GetSecondaryFireButton())
{
if (!_target.HasValue) _target = GetObjectClosestToAim();
if (_inputProfile.GetPrimaryFireButton())
{
OnPrimaryFire.Invoke(_target.Value);
}
if (_inputProfile.GetSecondaryFireButton())
{
OnSecondaryFire.Invoke(_target.Value);
}
}
else
{
_target = null;
}
if (_inputProfile.GetPrimaryFireButtonUp())
OnPrimaryFireStop.Invoke();
if (_inputProfile.GetSecondaryFireButtonUp())
OnSecondaryFireStop.Invoke();
}
/// <summary>
/// Finds the object within range closest to the players forward-vector
using _aimAssistLayerMask.
/// </summary>
/// <returns>Returns object closest to aim if any object is found, else
returns null.</returns>
ShootHit? GetObjectClosestToAim()
{
// Raycast
RaycastHit hit;
if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
out hit, aimAssistRadius, _aimAssistLayerMask))
{
if (hit.transform?.GetComponent<IShootTarget>() != null)
{
Debug.Log(hit.transform.name);
return new ShootHit { gameObject = hit.transform.gameObject,
point = hit.point };
}
}
float _closestDot = -2f;
GameObject _closestDotObject = null;
RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
QueryTriggerInteraction.Ignore);
// Get best dot from all objects within range
for (int i = 0; i < _hit.Length; i++)
{
if (_hit[i].transform.gameObject == this.gameObject ||
_hit[i].transform.GetComponent<IShootTarget>() == null)
continue;
Vector3 _dif = _hit[i].transform.position - transform.position;
float _newDot = Vector3.Dot(transform.forward.normalized,
_dif.normalized);
if (_newDot > _closestDot)
{
_closestDot = _newDot;
_closestDotObject = _hit[i].transform.gameObject;
}
}
if (!_closestDotObject)
return null;
// Make sure there are no object in the way of our best-dot-object
Collider[] colliders = _closestDotObject.GetComponents<Collider>();
Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
// Get closest collider
for (int i = 1; i < colliders.Length; i++)
{
Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
newPoint);
if (distanceToPoint > newDistanceToPoint)
{
point = newPoint;
distanceToPoint = newDistanceToPoint;
}
}
RaycastHit _rayhit;
if (Physics.Raycast(shootOrigin.position, point - transform.position,
out _rayhit, aimAssistRadius, _aimAssistLayerMask))
{
if (_rayhit.transform.gameObject != _closestDotObject)
{
return null;
}
}
Vector3 _vecToClosest = _closestDotObject.transform.position -
transform.position;
if (Vector3.Angle(transform.forward, _vecToClosest) <=
aimAssistMaxAngleToAssist)
{
return new ShootHit { gameObject = _closestDotObject, point = point
};
}
else
{
return null;
}
}
IEnumerator ChargeUpBeforeFirePrimary()
{
_isChargingPrimary = true;
yield return new WaitForSeconds(_chargeupTime);
_isChargingPrimary = false;
OnPrimaryFireStart.Invoke();
}
IEnumerator ChargeUpBeforeFireSecondary()
{
_isChargingSecondary = true;
yield return new WaitForSeconds(_chargeupTime);
_isChargingSecondary = false;
OnSecondaryFireStart.Invoke();
}
#if UNITY_EDITOR
private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;
Color oldColor = Gizmos.color;
float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
float coneDirection = -90f;
Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);
Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;
// Green Arc
Handles.color = new Color(0f, 1f, 0f, 0.25f);
Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);
Gizmos.color = oldColor;
}
#endif
}
`
This is the code attached to the projectile
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{
public GameObject Explosion;
public Transform Target;
Rigidbody _rigidbody;
public float speed = 1.0f;
void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
Collider targetCollider = Target.GetComponent<Collider>();
Vector3 targetDirection;
if (targetCollider)
targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
else
targetDirection = Target.position - transform.position;
_rigidbody.velocity = targetDirection.normalized * speed;
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
}
public void SetTarget(GameObject target)
{
this.Target = target.transform;
}
public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);
}
This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.
public class ProjectileSpawner : MonoBehaviour
{
public GameObject projectileInsert;
public GameObject projectileExtract;
public float projectileSpeed = 1.0f;
GameObject projectile;
public void Insert(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(target);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
public void Extract(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(gameObject);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
}
In the ProjectileSpawner, add a LayerMask field to filter out invalid collisions (set it in the inspector) for the non-homing projectile. You'll set this in the inspector to make the non-homing projectiles collide with the desired layers:
public LayerMask collisionLayers;
In Insert, find the ray going from the screen's center, and use it and the LayerMask as a parameter to SetTarget:
public void Insert(GameObject target)
{
if (projectile) return;
Ray centerRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0f));
projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(centerRay, collisionLayers);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
public void Extract(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(gameObject);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
Then in the ProjectileScript, add a bool field to remember if the projectile homes on a gameObject or if it follows a ray, a Ray field to remember such a ray, and a LayerMask field to remember what to collide with:
public bool isHoming;
public Ray TargetRay
public LayerMask collisionLayers;
Then, in public void SetTarget(GameObject target), set that bool to true:
public void SetTarget(GameObject target)
{
this.Target = target.transform;
isHoming = true;
}
And make a new public void SetTarget(Ray shootRay) that remembers a Ray and LayerMask and sets the bool to false:
public void SetTarget(Ray shootRay, LayerMask collisionLayers)
{
this.TargetRay = shootRay;
this.collisionLayers = collisionLayers;
isHoming = false;
}
Also, in ProjectileScript, you will need to change the FixedUpdate method to check if the bool is true, and if it is, then do the same as before. Otherwise, move along the ray and destroy it if it travels too far:
public float maxDistanceBeforeDestroy = 100f;
...
void FixedUpdate()
{
if (isHoming)
{
// _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
Collider targetCollider = Target.GetComponent<Collider>();
Vector3 targetDirection;
if (targetCollider)
targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
else
targetDirection = Target.position - transform.position;
_rigidbody.velocity = targetDirection.normalized * speed;
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
}
else
{
_rigidbody.velocity = TargetRay.direction.normalized * speed;
// Check if it has traveled too far
if ((transform.position - TargetRay.origin).magnitude > maxDistanceBeforeDestroy )
{
Destroy(gameObject);
}
}
}
Then, add an OnCollisionEnter method that doesn't do anything if the projectile is homing. But if it isn't, it checks if the collision matches the LayerMask, and if it does, it makes the explosion and destroys the projectile:
void OnCollisionEnter(Collision other)
{
if (isHoming)
{
return;
}
if( && ((1<<other.gameObject.layer) & collisionLayers) != 0)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion,
gameObject.transform.position,
gameObject.transform.rotation) as GameObject;
//destroy the projectile
Destroy(gameObject);
}
}
Your question is a bit vague and doesn't look like you have put a lot of effort into understanding the code and trying to alterate it. Anyway I'll do my best.
always being able to fire (indifferent if the object is in range)`
probably simply set aimAssistRadius = 0; or entirely remove the check
if (Vector3.Distance(_target.Value.gameObject.transform.position, transform.position) > aimAssistRadius)
{
_target = null;
}
shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.
The script you posted (probably not yours) seems to have the entire purpose of doing what you not want to do: Aim assist. Removing it probably changes a lot of things but the simpliest would be to simply set the ProjectileScript._rigidbody.velocity in the moment the projectile is instantiated. Unfortunately you didn't provide the code where this happens.
I don't see in which moment your ShootComponent interacts with the ProjectileScript but probably in one of those UnityEvents ... ?
But in general it would maybe simply look like
public class ProjectileScript : MonoBehaviour
{
public float speed = 1.0f;
private RigidBody _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<RigidBody>();
}
public void SetDirection(Vector3 direction)
{
_rigidbody.velocity = direction.normalized * speed;
}
}
and whereever you Instantiate the projectile do
var projectile = instantiatedObject.GetComponent<ProjectileScript>();
var direction = Camera.main.transform.forward;
projectile.SetDirection(direction);
as you can see you will have to make the
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
happen somewhere else since the code will not be target based anymore ... I would probably use OnCollisionEnter instead something like e.g.
private void OnCollisionEnter(Collision collision)
{
// maybe only collide with a certain tag
if(collision.gameObject.tag != "Target") return;
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}

unity make moveable sprite clickable

I have a player sprite that moves anywhere on the screen clicked. I am trying to make a player info panel popup if the player sprite is clicked.
But unfortunately I only get the player moving a couple of pixels. I have a Box Collider 2d added to the sprite and an event trigger set to Pointer Click to run the method ShowPlayerInfoPanel
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
//Player Movement
float speed = 2f;
Vector2 targetPos;
private Rigidbody2D myRigidbody;
private Animator myAnim;
private static bool playerExists;
public static PlayerController instance;
public string exitPortal;
public bool startMoving;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
//Player Info
public string displayName;
public string coins;
//Player Panel display
public GameObject playerInfoPanel;
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
if(instance == null){
instance = this;
} else {
Destroy(gameObject);
}
DontDestroyOnLoad(transform.gameObject);
targetPos = transform.position;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
startMoving = true;
}
if ((Vector2)transform.position != targetPos && startMoving)
{
Move();
} else {
myAnim.SetBool("PlayerMoving", false);
}
}
void Move()
{
Vector2 oldPos = transform.position;
transform.position = Vector2.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);
//transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, smoothTime);
Vector2 movement = (Vector2)transform.position - oldPos;
myAnim.SetBool("PlayerMoving", true);
myAnim.SetFloat("Horizontal", movement.x);
myAnim.SetFloat("Vertical", movement.y);
}
public void ShowPlayerInfoPanel()
{
Debug.Log("hi");
PlayerInfoPanel playerInfo = playerInfoPanel.GetComponent<PlayerInfoPanel>();
playerInfo.DisplayName.text = displayName;
playerInfo.Coins.text = coins;
playerInfoPanel.SetActive(true);
}
}
With a collider on your gameObject you can just use OnMouseDown to detect when the object is clicked.
void OnMouseDown()
{
ShowPlayerInfoPanel();
}

Shoot bullet to direction of last player position

I am trying to code a drone that is shooting a laser-bullet to the last position of the player. The bullet should also rotate to the players position.
I have following script, but it is not shooting for some reason.
using System.Collections.Generic;
using UnityEngine;
public class DroneShoot: MonoBehaviour
{
public Transform bulletspawn;
public Rigidbody2D bulletPrefab;
public float bulletSpeed = 750;
public float bulletDelay;
private Transform player;
private Rigidbody2D clone;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
StartCoroutine(Attack());
}
IEnumerator Attack()
{
yield return new WaitForSeconds(bulletDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Quaternion rotation = Quaternion.LookRotation(player.transform.position, bulletspawn.transform.position);
bulletspawn.rotation = rotation;
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
StartCoroutine(Attack());
}
}
}
It looks like it will only try to fire again if it is able to fire the first time because StartCoroutine is inside the distance check.
I think it should keep trying to shoot forever.
IEnumerator Attack()
{
while(true){
yield return new WaitForSeconds(shootDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Quaternion rotation = Quaternion.LookRotation(player.transform.position);
bulletspawn.rotation = rotation;
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
}
}
}
I have a solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneShoot: MonoBehaviour
{
public Transform bulletspawn;
public Rigidbody2D bulletPrefab;
public float bulletSpeed = 750;
public float bulletDelay;
private Transform player;
private Rigidbody2D clone;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("spieler").GetComponent<Transform>();
StartCoroutine(Attack());
}
IEnumerator Attack()
{
yield return new WaitForSeconds(bulletDelay);
if (Vector3.Distance(player.transform.position, bulletspawn.transform.position) < 20)
{
Vector3 difference = player.position - bulletspawn.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
bulletspawn.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
clone = Instantiate(bulletPrefab, bulletspawn.position, bulletspawn.rotation);
clone.AddForce(bulletspawn.transform.right * bulletSpeed);
StartCoroutine(Attack());
}
}
}

Categories

Resources