[2D] player able to walk through the walls HELP

Updated on August 1, 2018 in  [G] Say Hello!
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
1 on August 1, 2018

btw, i am using tilemap collisions cause i made a tilemap, and for the player i have put a box collider and 2d rigidbody, heres my code: 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Player : MonoBehaviour {
    private float axisX;
    private float axisY;
    private Rigidbody2D rb;
    public Slider healthBarRef;
    public float jumpHeight;
    public int speed;
    public float health;
    // Use this for initialization
    public float respawnX;
    public float respawnY;
    void Start () {
        speed = 200;
        jumpHeight = 300.0f;
        rb = GetComponent<Rigidbody2D>();
        
    }
    
    // Update is called once per frame
    void Update () {
        axisX = Input.GetAxis("Horizontal");
        transform.Translate(new Vector3(axisX, 0) * speed * Time.deltaTime);
        if(Input.GetKeyDown(KeyCode.Space)) {
            rb.velocity = new Vector3(0f, jumpHeight, 0f);
        }
        health = healthBarRef.GetComponent<CharacterHealth>().currentHealth;
        if(health == 0.0f) {
            Debug.Log("You Have chickne");
            transform.position = new Vector3(respawnX, respawnY, 0);
            health = 100;
        }
    }
}

 

heres a gif showing my problem: https://gyazo.com/9c75c836d3ed69a7d34f393f476c6739

it would also be great if someone can help me with the jittery camera movement. Heres the code: 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
    public Transform target;
    public float smoothTime = 0.15f;
    Vector3 velocity = Vector3.zero;
    public Vector3 offset;
    
    void FixedUpdate(){
        
        Vector3 targetPos = target.position;
        
        transform.position = Vector3.SmoothDamp(transform.position + offset, targetPos, ref velocity, smoothTime);
    }
}

  • Liked by
  • Eethical
Reply
0 on August 1, 2018

Moving through walls is because you’re using transform.Translate instead of using the rigidbody. You can only use translate with collision if the rb is kinematic.

 

Jittery camera is because you’re using FixedUpdate instead of Update. FixedUpdate only fires about every 0.2s opposed to about 0.016 for normal Update.

  • Liked by
Reply
Cancel