I'm a beginner at coding and wanted to make a quick little program to test my googling skills so far. I'm trying to make the player GameObject be given a speed boost when it collides with the "speed" GameObject and it doesn't work (the cube can still move but it isn't affected when colliding with the speed). Below is my player movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed = 10f;
void Update()
{
Vector3 position = transform.position;
if (Input.GetKey("w")){
position.y += moveSpeed * Time.deltaTime;
}
if (Input.GetKey("s")){
position.y -= moveSpeed * Time.deltaTime;
}
if (Input.GetKey("d")){
position.x += moveSpeed * Time.deltaTime;
}
if (Input.GetKey("a")){
position.x -= moveSpeed * Time.deltaTime;
}
transform.position=position;
}
}
And here is the power-up script. I used a Debug.Log()
to figure out where the problem is at the line under the private void
:
using UnityEngine;
public class Speed : MonoBehaviour
{
public float speedIncrease = 5f;
private void OnTriggerEnter2D(Collider2D collision){
if (collision.tag == "Player"){
GameObject player = collision.gameObject;
Player playerScript = player.GetComponent<Player>();
if (playerScript){
playerScript.moveSpeed += speedIncrease;
}
}
}
}
I come from Blender Stack Exchange where we provide all pieces of info we feel are relevant. Please let me know if that's not the case here or if I left something out.
EDIT here is what the objects look like in the inspector
rigidbody
on the object receiving the collision, and make sure theIsTrigger
is checked in the collision box that sent the collision. \$\endgroup\$CompareTag()
over.tag ==
\$\endgroup\$