On Line Renderer will Instantiate GameObject to make a bridge (Unity c#) - c#

I am trying to make a bridge using Line Renderer.
With this script i write on mouse click straight line and when i want somehow use
"startPos" and "endPos" to make that streched gameobject (sprite renderer)
in 2d game.. how to write down Instatiate function? I am lost in this..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawBridge : MonoBehaviour
{
private LineRenderer lineRend;
private Vector2 mousePos;
private Vector2 startMousePos;
[SerializeField]
private SpriteRenderer spriteRender;
private float distance;
[SerializeField]
GameObject spawnBridge;
private void Start()
{
lineRend = GetComponent<LineRenderer>();
lineRend.positionCount = 2;
spriteRender = GetComponent<SpriteRenderer>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
startMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
StartDrawn();
}
}
void StartDrawn()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 startPos = new Vector3(startMousePos.x, startMousePos.y, 0f);
lineRend.SetPosition(0, startPos);
Vector3 endPos = new Vector3(mousePos.x, mousePos.y, 0f);
lineRend.SetPosition(1, endPos);
distance = (mousePos - startMousePos).magnitude;
// Instantiate(spawnBridge, startPos, endPos, transform.rotation.);
}
}

Related

Sprite not Appearing in Unity 2D Game

I'm creating a 2D Top Down game for practice and I need a little bit of help. For context, it's a 2D Top Down Shooter game, where you can move and shoot enemies. The enemies have a basic radius system where if the player gets within the radius, it'll approach the player.
Now I'm making a game mechanic where the player can hide in a cardboard box, the player can press 'E' and he'll suddenly become a cardboard box, where if the player is in the cardboard box, the enemy doesn't detect him even if the player's within the radius. Yes, just like in Metal Gear. Now I've created the prefabs and everything and functionality-wise, it works perfectly. If you press 'E' the enemy cannot detect you.
Now the small problem is that the cardboard box didn't appear, so it's just the player disappearing entirely. I do not know what caused this problem.
For context, these are my scripts. Feel free to read them, or not :)
PlayerController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public GameObject bulletPrefab;
public GameObject player;
private Rigidbody2D rb2d;
private Vector2 moveDirection;
[SerializeField] private Camera cam;
[SerializeField] private GameObject gunPoint;
public bool isHiding = false;
[SerializeField] private GameObject cardboardBox;
[SerializeField] private GameObject gunSprite;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
cardboardBox.SetActive(false); // Hide the cardboard box when the game starts
gunSprite.SetActive(true); // Show the gun sprite when the game starts
}
// Update is called once per frame
void Update()
{
CheckCursor();
ProcessInputs();
// Make the camera follow the player
cam.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, cam.transform.position.z);
// Check if player pressed the "E" key to toggle the cardboard box
if (Input.GetKeyDown(KeyCode.E))
{
isHiding = !isHiding; // Toggle the isHiding variable
cardboardBox.SetActive(isHiding); // Show/hide the cardboard box accordingly
// If player is hiding, stop player movement
if (isHiding)
{
moveDirection = Vector2.zero;
player.GetComponent<SpriteRenderer>().enabled = false;
cardboardBox.GetComponent<SpriteRenderer>().enabled = true;
gunSprite.SetActive(false); // Hide the gun sprite when the player is hiding
}
else
{
player.GetComponent<SpriteRenderer>().enabled = true;
cardboardBox.GetComponent<SpriteRenderer>().enabled = false;
gunSprite.SetActive(true); // Show the gun sprite when the player is not hiding
}
}
}
private void FixedUpdate()
{
if (!isHiding) // Only allow player to move if they are not hiding in the cardboard box
{
Movement();
}
}
private void CheckCursor()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 characterPos = transform.position;
if (mousePos.x > characterPos.x)
{
this.transform.rotation = new Quaternion(0, 0, 0, 0);
}
else if (mousePos.x < characterPos.x)
{
this.transform.rotation = new Quaternion(0, 180, 0, 0);
}
}
private void Movement()
{
// TODO : Implementasi movement player
rb2d.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
private void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY);
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
}
private void Shoot()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 gunPointPos = gunPoint.transform.position;
Vector3 direction = (mousePos - gunPointPos).normalized;
GameObject bullet = Instantiate(bulletPrefab, gunPointPos, Quaternion.identity);
bullet.GetComponent<Bullet>().Init(direction);
}
}
EnemyController script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public Transform player;
public float moveSpeed = 5f;
public float detectionRadius = 5f;
public int maxHealth = 1;
private int currentHealth;
private Rigidbody2D rb2d;
private Vector2 movement;
private void Start()
{
rb2d = this.GetComponent<Rigidbody2D>();
currentHealth = maxHealth;
}
private void Update()
{
float distanceToPlayer = Vector2.Distance(transform.position, player.position);
if (player != null && distanceToPlayer <= detectionRadius && !player.GetComponent<PlayerController>().isHiding)
{
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb2d.rotation = angle;
direction.Normalize();
movement = direction;
}
else
{
movement = Vector2.zero;
}
}
void FixedUpdate()
{
moveCharacter(movement);
}
private void moveCharacter(Vector2 direction)
{
rb2d.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
public void DestroyEnemy()
{
Destroy(gameObject);
}
}
Bullet script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private float speed;
[SerializeField] private Vector3 direction;
public void Init(Vector3 direction)
{
this.direction = direction;
this.transform.SetParent(null);
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
}
// Update is called once per frame
void Update()
{
this.transform.position += transform.right * speed * Time.deltaTime;
}
// TODO : Implementasi behaviour bullet jika mengenai wall atau enemy
private void OnTriggerEnter2D(Collider2D other)
{
switch(other.gameObject.tag)
{
case "Wall":
Destroy(gameObject);
break;
case "Enemy":
Destroy(gameObject);
other.gameObject.GetComponent<EnemyController>().DestroyEnemy();
break;
}
}
}
I've tried tinkering my scripts, I've tried checking if there are any missing components in the cardboard box game object but to no avail. Although I might be wrong on the Unity part since I'm fairly certain that the script isn't the problem here, again might be wrong.
I appreciate all the help I can get, thank you for reading until here

How to control the curve of a jump mechanic in Unity while using the Rigidbody2D's velocity?

I'm making a platformer controller using the new Input System and trying to control the curve for jumping... I've figured out how to add a damp for the horizontal movement which give the horizonal movement a bit of a slippery feel. But I cannot figure out how to control curve for the Jump. The problem now is I'm using a Player Input Component and Unity Events to control the Move and Jump. And the jump is using rb.velocity.y.
How do I control my Jump curve?
Here is the current curve:
I want to controle the acceleration and deacceleration of the curve:
Here is the curve I'd like to achieve with jumping
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private const float GroundedRadius = 0.2f;
[SerializeField] private float smoothInputSpeed = .2f;
[SerializeField] private float speed = 8f;
[SerializeField] private float jumpingPower = 12f;
[SerializeField] private float fallPower = 2f;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
private Vector2 _smoothMove = Vector2.zero;
private Vector2 _smoothInputVelocity = Vector2.zero;
private Vector2 _move = Vector2.zero;
private bool _isFacingRight = true;
void Update()
{
_smoothMove = Vector2.SmoothDamp(_smoothMove, _move, ref _smoothInputVelocity, smoothInputSpeed);
rb.velocity = new Vector2(_smoothMove.x * speed, rb.velocity.y);
if (!_isFacingRight && _move.x > 0f || _isFacingRight && _move.x < 0f)
{
Flip();
}
}
public void Move(InputAction.CallbackContext context)
{
_move = context.ReadValue<Vector2>();
}
public void Jump(InputAction.CallbackContext context)
{
if (context.performed && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
if (context.canceled && rb.velocity.y > 0f)
{
var velocity = rb.velocity;
var gravity = rb.gravityScale;
velocity = new Vector2(velocity.x, (velocity.y * gravity * fallPower)); // fall faster if cancelled
rb.velocity -= velocity;
}
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, GroundedRadius, groundLayer);
}
private void Flip()
{
_isFacingRight = !_isFacingRight;
var transform1 = transform;
Vector3 localScale = transform1.localScale;
localScale.x *= -1f;
transform1.localScale = localScale;
}
}

I'm trying to make a Instance at the mouse position but it doesn't work

I'm trying to make an instance at the mouse pos, but when it makes the instance, it's way off and is really far out from my mouse. How could I fix this? Here is my code:
using UnityEngine;
using System.Collections;
// note
// note
public class attack : MonoBehaviour
{
public Transform prefab;
void Update()
{
Vector3 mousePos = Input.mousePosition;
if (Input.GetMouseButtonDown(0))
Instantiate(prefab, mousePos, Quaternion.identity);
}
}
Input.mousePosition is in screen pixel space!
You most probably rather want to use Camera.ScreenToWorldSpace
public class attack : MonoBehaviour
{
public Transform prefab;
// you will need to figure this out
public float desiredDistanceInFrontOfCamera;
[SerializeFiel] private Camera _camera;
private void Awake()
{
if(!_camera) _camera = Camera.main;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = desiredDistanceInFrontOfCamera;
Vector3 spawnPos = _camera.ScreenToWorldPoint(mousePos);
Instantiate(prefab, spawnPos, Quaternion.identity);
}
}
}

how do i drag and launch in untiy 2d?

I am a newbie in c# and i have been trying to get some code that will help me launch my character in the opposite direction of the drag. Like Angry Birds but i don't want the character to move while i am dragging. Here is my script that i copied from a video and it isn't working.
`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbMovement : MonoBehaviour
{
public float launchSpeed = 100;
Vector3 _initialPosition;
Rigidbody2D rb;
private Vector2 directionToInitialPosition;
private void Awake()
{
_initialPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
directionToInitialPosition = _initialPosition - transform.position;
}
private void OnMouseUp()
{
rb.AddForce(directionToInitialPosition *launchSpeed);
}
private void OnMouseDrag()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(newPosition.x, newPosition.y);
}
}
`
help me with a script that will launch my character opposite of the drag. Thanks in advance :)
Why don't you just remove the
private void OnMouseDrag()
{
Vector3 newPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(newPosition.x, newPosition.y);
}
this part of the script means that everytime the player drag the mouse/touch then the gameobject will follow the mouse. Because you don't want it, you can just remove it to
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OrbMovement : MonoBehaviour
{
public float launchSpeed = 100;
Vector3 _initialPosition;
Rigidbody2D rb;
private Vector2 directionToInitialPosition;
private void Awake()
{
_initialPosition = transform.position;
rb = GetComponent<Rigidbody2D>();
directionToInitialPosition = _initialPosition - transform.position;
}
private void OnMouseUp()
{
rb.AddForce(directionToInitialPosition *launchSpeed);
}
}

Rotating gameobject with Joystick

Trying to rotate my gameObject with Joystick, I did previously a script that gameobject was facing mouseInput and I want exactly the same but while using joystick?
public class FaceMouse : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
Rotation();
}
}
void Rotation()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y);
transform.up = direction;
}
}
I was searching and I found this script, but gameobject doesn't rotate like clock, it rotate my gameobject on other axis, any idea how to make my object to copy JOYTICK movement just like in first script ?
public class PlayerMovements : MonoBehaviour
{
public FixedJoystick joystick;
public float speed = 10f;
public float roatateSpeed = 40f;
public GameObject rb;
private void Start()
{
rb = GetComponent<GameObject>();
}
private void Update()
{
float horizontal = joystick.Horizontal;
float vertical = joystick.Vertical;
Vector3 frameMovement = new Vector3(horizontal, 0f, vertical);
Quaternion rotation = Quaternion.LookRotation(frameMovement);
transform.rotation = rotation;
}
}
Try This
float AxisFactor = 90;
transform.localEulerAngles += new Vector3(vertical, horizontal, 0)*AxisFactor*Time.deltaTime;

Categories