Home > Blockchain >  How can I get transform.position.z to increase by 5 when the up arrow is clicked?
How can I get transform.position.z to increase by 5 when the up arrow is clicked?

Time:01-06

Thank you in advance!

I can't get this to work

What am I doing wrong here?

My code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCamera : MonoBehaviour {
    void Start() {}
    void Update() {
        if(Input.GetKeyDown(KeyCode.UpArrow)) {
            transform.position  = new Vector3(0, 0, 1) * Time.deltaTime * 60;}}}

I want the transform to increase by a z of 5. When I click the up arrow, it increase by a seemingly random, several-decimal-place-long float. What in the world am I doing wrong??

CodePudding user response:

Well what you are doing makes little sense for a Single-Event click input.

Time.deltaTime only makes sense for a continuous smooth movement and is used to convert the given value from value per frame into value per second regardless the frame rate.


Also what you did here makes even less sense. The Time.deltaTime is different each frame! Therefore it makes no sense at all to store it initially and then use it later on.

And well your code would then further only work if your frame rate is exactly 50 frames per second.


If you want to move your object by a fixed 5 units up then simply do so

public class MoveCamera : MonoBehaviour 
{
    private void Update() 
    {
        if(Input.GetKeyDown(KeyCode.UpArrow))
        {
            transform.position  = Vector3.up * 5f;
        }
    }
}

CodePudding user response:

OK works now. What I changed:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveCamera : MonoBehaviour {
    private float time;
    void Start() {time = Time.deltaTime;}
    void Update() {
        if(Input.GetKeyDown(KeyCode.UpArrow)) {
            transform.position  = new Vector3(0, 0, 1) * time * 250;}}}
  • Related