I am trying to make my 3d platformer, but when I made simple movement script, whenever I press forward (W), it goes forward, no issue, but when i rotate my camera, it still goes in that same position. I want it to be relative to the camera, so how do I fix this? Here is movement script |
v
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
private Vector3 PlayerMovementInput;
[SerializeField] private Rigidbody rb;
[Space]
[SerializeField] private float speed;
[SerializeField] private float jumpforce;
// Update is called once per frame
void Update()
{
PlayerMovementInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
MovePlayer();
}
private void MovePlayer()
{
Vector3 MoveVector = transform.TransformDirection(PlayerMovementInput) * speed;
rb.velocity = new Vector3(MoveVector.x, rb.velocity.y, MoveVector.z);
}
}
On line 24, instead of using transform
, which is a shortcut to the Transform that this script is on, use the Transform of the camera in question.
I don’t really understand. How do I use the transform component of the camera instead, since it’s the movement script? I’m using a Cinemachine Freelook one by the way.
Okay, I understand now, but how do I choose/add the .transform component of the camera, while the movement script is attached to my object?
By making a public Transform variable in this script and using that to access it.
Don’t forget to drag the camera into the above field.
Referencing variables, fields, methods (anything non-static) in other script instances:
https://discussions.unity.com/t/833085/2
https://discussions.unity.com/t/839310
REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.
Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.
That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.
1 Like