I am fairly new to C# and unity and I am trying to make a square jump with a Vector2 but for some reason the square wont move. Here is the code for you to see:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float Jump;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Jump = Input.GetAxis("Jump");
if (Jump == 1)
{
new Vector2(0, 1);
}
}
}
try this
//player must have a rigidbody2D and a box colider
public float moveSpeed = 5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
void Jump()
{
if (Input.GetButtonDown("Jump"))
{
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
}
}
Related
I am trying to do ground detection for a 2d platformer, but my physics check is always returning true. I am reusing code that I have used a many times before:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Header("MOVEMENT")]
public float speed;
float inputX;
[Header("JUMPING")]
public float jumpForce;
public Transform feet;
public Vector2 checkSize;
public bool isGrounded;
public LayerMask layers;
public int extraJumps = 1;
int jumpTracker;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
inputX = Input.GetAxisRaw("Horizontal");
isGrounded = Physics2D.OverlapBox(feet.position, checkSize, 0f, layers);
if(Input.GetKeyDown(KeyCode.Space))
{
if (isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTracker = extraJumps;
}
else
{
if(jumpTracker > 0)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
jumpTracker--;
}
}
}
}
private void FixedUpdate()
{
rb.velocity = new Vector2(inputX * speed, rb.velocity.y);
}
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(feet.position, checkSize);
}
}
In the scene there is a Tilemap with a composite collider tagged as ground that the player is colliding with.
I have tried everything I can think of and still have no idea what is causing this issue. Any help would be greatly appreciated.
So as previously said I need the bullet to follow the enemy. I'm making a 2d Game and just can't figure out how. I'll appreciate it if someone could help me. Here are my scripts.
Bullet Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFire : MonoBehaviour
{
float moveSpeed = 25f;
Rigidbody2D rb;
Monster target;
Vector2 moveDirection;
public float firespeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.right * firespeed * Time.deltaTime, Space.Self);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log(collision.transform.name);
Destroy(gameObject);
}
}
Enemy script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Monster : MonoBehaviour {
[SerializeField]
GameObject bullet;
float fireRate;
float nextFire;
public Image BosshealthBar;
public float BosshealthAmount = 100;
public GameObject effect;
// Use this for initialization
void Start () {
fireRate = 1f;
nextFire = Time.time;
}
// Update is called once per frame
void Update () {
CheckIfTimeToFire ();
if (BosshealthAmount <= 0)
{
Destroy(gameObject);
}
}
void CheckIfTimeToFire()
{
if (Time.time > nextFire) {
Instantiate (bullet, transform.position, Quaternion.identity);
nextFire = Time.time + fireRate;
}
}
public void TakeDamage(float Damage)
{
BosshealthAmount -= Damage;
BosshealthBar.fillAmount = BosshealthAmount / 100;
}
public void Healing(float healPoints)
{
BosshealthAmount += healPoints;
BosshealthAmount = Mathf.Clamp(BosshealthAmount, 0, 100);
BosshealthBar.fillAmount = BosshealthAmount / 100;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag.Equals("BulletPlayer"))
{
TakeDamage(10);
Instantiate(effect, transform.position, Quaternion.identity);
}
}
}
Something like this may help u
Vector3 direction = Target.position - Bullet.position;
float distance = direction.magnitude;
float TargetSpeed = 5
Vector3 Force = direction.normalized * ForceMagnitude;
Bullet.AddForce(Force);
But you will need to add it in yourself since i can't tell how your code speceficly works
In my Unity my Player gets everytime stuck in the collider when he has a big force (If he falls from a high place, The Gravity Scale or his jumppower is high). In the picture you can see Colliders and Renderer.
Only one Component is not on in screen at the platformcomponents, Tilemap.
Here is my code for Playermovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private LayerMask platformsLayerMask;
private Rigidbody2D rigidbody2d;
private BoxCollider2D boxCollider2d;
private void Awake()
{
rigidbody2d = transform.GetComponent<Rigidbody2D>();
boxCollider2d = transform.GetComponent<BoxCollider2D>();
}
private void Update()
{
if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
{
float jump_power = 17.5f;
rigidbody2d.velocity = Vector2.up * jump_power;
}
HandleMovement();
}
private bool IsGrounded()
{
RaycastHit2D raycastHit2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .1f, platformsLayerMask);
return raycastHit2d.collider != null;
}
private void HandleMovement()
{
float moveSpeed = 10f;
if (Input.GetKey(KeyCode.A))
{
rigidbody2d.velocity = new Vector2(-moveSpeed, rigidbody2d.velocity.y);
}
else if (Input.GetKey(KeyCode.D))
{
rigidbody2d.velocity = new Vector2(+moveSpeed, rigidbody2d.velocity.y);
}
else
{
rigidbody2d.velocity = new Vector2(0, rigidbody2d.velocity.y);
}
}
}
Have you tried setting the player's rigidbody collision detection to continuous? If the collision detection is set to discrete, it's really easy to come accross this kind of problem when using the built in physics system
I don't want my player to jump in the air but I can't seem to find anything out.
This is what I have. They can jump, but they can jump forever and that's a problem.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed = 5f;
public float jumpSpeed = 8f;
private float movement = 0f;
public bool alive;
private Rigidbody2D rigidBody;
// Use this for initialization
void Start () {
rigidBody = GetComponent<Rigidbody2D> ();
// Use this for initialization
}
// Update is called once per frame
void Update () {
movement = Input.GetAxis ("Horizontal");
if (movement > 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else if (movement < 0f) {
rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
}
else {
rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
}
if(Input.GetButtonDown ("Jump")){
rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
}
}
}
An simple option is to maintain a boolean such as _inAir that gets set to true when the player first jumps, and to false when their RigidBody2D collides with the ground (see, e.g., OnCollisionEnter2D).
Then, the check if(Input.GetButtonDown ("Jump")){ becomes
if (!_inAir && Input.GetButtonDown("Jump")) {
I'm trying to get my main camera to move upwards on the Y axis slowly only after the left mouse button is clicked.
Here is my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class CameraPanUp : MonoBehaviour
{
public float speed = 5f;
public Transform target;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 targetCamPos = target.position + offset;
transform.position = Vector3.Lerp(transform.position, targetCamPos, speed * Time.deltaTime);
if (Input.GetMouseButtonDown(0))
{
}
}
}
I'm unsure what to put in the if statement above. I tried using transform.Translate before and it just made the Camera move up in small increments every time i left click. Why is that? Any help would be gladly appreciated.
One option is to use Coroutines:
Coroutine moveCoroutine;
IEnumerator StartMovingUp() {
float moveSpeed = 2f;
while(true) {
transform.Translate(0, moveSpeed * Time.deltaTime, 0);
yield return null;
}
}
void Update() {
if (Input.GetMouseButtonDown(0) && moveCoroutine == null) {
moveCoroutine = StartCoroutine(StartMovingUp());
}
}
another is doing it in the Update function with fields for state. Anything more may make the code too complicated.
bool isMovingUp;
float moveSpeed = 2f;
void Update() {
if (Input.GetMouseButtonDown(0)) {
isMovingUp = true;
}
if (isMovingUp) {
transform.Translate(0, moveSpeed * Time.deltaTime, 0);
}
}