Unity Player character is not moving - c#

I have a script to move my character(Player) in unity. The script is fine and it does not have any errors, Although when i enter
play mode and try to use the arrows to move my character, it does not move at all, i can't figure out what is the problem.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 1f;
public float CollisionOffset = 0.05f;
public ContactFilter2D movementFilter;
Vector2 movementInput;
Rigidbody2D rb;
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
if (movementInput != Vector2.zero) {
int count = rb.Cast(
movementInput,
movementFilter,
castCollisions,
moveSpeed * Time.fixedDeltaTime + CollisionOffset
);
if (count == 0) {
rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
}
}
}
void onMove(InputValue movementValue) {
movementInput = movementValue.Get<Vector2>();
}
}
Unity version: 2022.2.0b14
Input System: version 1.2.0
Any help is appreciated.

OnMove not executing because it's OnMove not onMove. this is reference directly by new input system. So the Function name should be On+[ActionName] and here when you are using Default InputActions so Move -> OnMove.

Related

2D character is not moving in Unity, using the keys. Script seems to be correct. Please verify the code and the Inspector

![This is how my Inspector looks like](inspector image)
And here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public float speed = 10f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector2 Movement = Vector2.zero;
Movement.y = v;
Movement.x = h;
transform.Translate(Movement * speed * Time.deltaTime);
}
} // class
And no, increasing the speed to check if its just not moving really slow, did not help :(
You need to set correct value in inspector or in start funciton.
void Start()
{
speed = 10f;
}
inspector image

After transferring my project from my PC to a laptop a piece of code doesn't work

I'm learning Unity and am following a guide. In the game you have to fly a rocket through an obstacle course. This is my code for the movement of the rocket:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
Rigidbody rb;
[SerializeField] float mainThrust = 100f;
[SerializeField] float rotationSpeed = 50f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
ProcessThrust();
ProcessRotation();
}
void ProcessThrust()
{
if (Input.GetKey(KeyCode.Space))
{
//Boost
rb.AddRelativeForce(Vector3.up * mainThrust * Time.deltaTime);
}
}
void ProcessRotation()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
//Rotate left
ApplyRotate(rotationSpeed);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
//Rotate right
ApplyRotate(-rotationSpeed);
}
}
void ApplyRotate(float rotationPreFrame)
{
rb.freezeRotation = true; // freezing rotation so we can manually rotate
transform.Rotate(0, 0, 1 * rotationPreFrame * Time.deltaTime);
rb.freezeRotation = true; // unfreezing rotation so the physics system can take over
}
}
For some reason I can't fly the rocket, only rotate left and right. Got any idea why?
Did you check if you have a rigidbody applied on the object?
If so, check that inside Project settings > Player > Active input handling is set to BOTH.
Anyway, try to change your input system to the new one:
https://learn.unity.com/project/using-the-input-system-in-unity

how can i convert a transform into a float

I am trying to take the current position of something once when collided and im not sure how to
do that could anyone help me out please?
The problem i have is that the script is grabbing the playerLocation constantly i need it so it grabs it once it collides.
basically when my object colides with something it moves towards a diferent object but i dont want it to follow it constantly i want it to get the position of that 1 object only once it has collided.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CircleMover : MonoBehaviour
{
public float speed = 10.0f;
public Transform playerLocation;
public float redirectSpeed;
public bool isCurrentlyColliding;
Vector3 playerposition;
private Rigidbody2D rb;
private Vector2 screenBounds;
// Start is called before the first frame update
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(-speed, 0);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update()
{
//if (transform.position.x < -11.6f)
//{
// Destroy(this.gameObject);
//}
if (isCurrentlyColliding)
{
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("CopyCat"))
{
playerposition = (playerLocation.transform.position);
isCurrentlyColliding = true;
}
}
}
The reason it grabs the playerLocation constantly because you are using isCurrentlyColliding which you are never making false and also using it in Update() method which calls every frame.
You can do two things (choose whichever goes well with your code) :
by making isCurrentlyColliding false inside Update() method like this:
void Update()
{
if (isCurrentlyColliding)
{
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
isCurrentlyColliding = false;
}
}
by removing isCurrentlyColliding and setting transform.position directly inside OnTriggerEnter2D() method like this:
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("CopyCat"))
{
playerposition = (playerLocation.transform.position);
transform.position = Vector2.MoveTowards(transform.position, playerposition.transform.position, redirectSpeed * Time.deltaTime);
}
}

SetActive(True) not working after build but okay in the unity editor

I can't solve this problem where i want to hide and unhide a gameobject(UI) when i move using a VR controller. It came out fine in the editor but after build for the oculus quest(android), it stays inactive. anyone can help me? i put a list of UI that need to be hidden and wanted to set it active when the camera is not moving and hide when it is moving
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.UI;
public class ContinuousMovement : MonoBehaviour
{
//This script is used to make the VR Camera moves continuous using the analog
public float speed = 1;
public XRNode inputSource;
public float gravity = -9.81f;
public LayerMask groundLayer;
public float additionalHeight = 0.2f;
public List<GameObject> UiToBeHidden;
private float fallingSpeed;
private XRRig rig;
private Vector2 inputAxis;
private CharacterController character;
// Start is called before the first frame update
void Start()
{
character = GetComponent<CharacterController>();
rig = GetComponent<XRRig>();
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(true);
}
}
// Update is called once per frame
void Update()
{
CapsuleFollowHeadset();
InputDevice device = InputDevices.GetDeviceAtXRNode(inputSource);
device.TryGetFeatureValue(CommonUsages.primary2DAxis, out inputAxis);
Quaternion headYaw = Quaternion.Euler(0, rig.cameraGameObject.transform.eulerAngles.y, 0);
Vector3 direction = headYaw * new Vector3(inputAxis.x, 0, inputAxis.y);
character.Move(direction * Time.fixedDeltaTime * speed);
if (inputAxis.x == 0 && inputAxis.y == 0)
{
Debug.Log("static");
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(true);
}
}
else
{
Debug.Log("moving");
foreach (GameObject ui in UiToBeHidden)
{
ui.SetActive(false);
}
}
}
private void FixedUpdate()
{
//gravity
bool isGrounded = CheckIfGrounded();
if (isGrounded)
fallingSpeed = 0;
else
fallingSpeed += gravity * Time.fixedDeltaTime;
character.Move(Vector3.up * fallingSpeed * Time.fixedDeltaTime);
}
void CapsuleFollowHeadset()
{
character.height = rig.cameraInRigSpaceHeight + additionalHeight;
Vector3 capsuleCenter = transform.InverseTransformPoint(rig.cameraGameObject.transform.position);
character.center = new Vector3(capsuleCenter.x, character.height /2 + character.skinWidth, capsuleCenter.z);
}
bool CheckIfGrounded()
{
//tells us if on ground
Vector3 rayStart = transform.TransformPoint(character.center);
float rayLength = character.center.y + 0.01f;
bool hasHit = Physics.SphereCast(rayStart, character.radius, Vector3.down, out RaycastHit hitInfo, rayLength, groundLayer);
return hasHit;
}
}
I had exactly the same problem. The solution that works for me is changing the build setting.
Build Setting --> Player Settings --> Player --> Other Setting --> Api Compatibility level ( Change from .Net Standard 2.0 --> .Net 4.x)
That should work for you as well!

Why when i attach a script to the flashlight nothing happen ?

What i want to do is when the flashlight is on to be able to rotate the flashlight around with the mouse. But when i attach the script to the Flashlight i'm not getting any errors just nothing happen when i move the mouse around. I tried to attach the script to the GameObject i also tried to attach the script to the EthanRightHand but nothing.
But if i will attach the script to the ThirdPersonController it will rotate the character. But i want to rotate only the flashlight when it's on or to make it maybe nicer to rotate the EthanRightHand when the flashlight is on.
I can make the flashlight in the second script to be public static. But that is not the point. The problem is the first script the ObjectRotator only work on the ThirdPersonController.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectRotator : MonoBehaviour
{
int speed;
float friction;
float lerpSpeed;
private float xDeg;
private float yDeg;
private Quaternion fromRotation;
private Quaternion toRotation;
// Use this for initialization
void Start()
{
speed = 3;
friction = 3f;
lerpSpeed = 3f;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0))
{
xDeg -= Input.GetAxis("Mouse X") * speed * friction;
yDeg += Input.GetAxis("Mouse Y") * speed * friction;
fromRotation = transform.rotation;
toRotation = Quaternion.Euler(yDeg, xDeg, 0);
transform.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);
}
}
}
And the flashlight script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;
public class Flashlight : MonoBehaviour
{
[SerializeField]
Transform someBone;
Light flashlight;
// Use this for initialization
void Start()
{
flashlight = GameObject.FindGameObjectWithTag("Flashlight").GetComponent<Light>();
transform.parent = someBone;
}
// Update is called once per frame
void Update()
{
transform.localRotation = someBone.localRotation;
transform.localScale = someBone.localScale;
if (Input.GetKeyDown(KeyCode.F))
{
if (flashlight.enabled)
{
flashlight.enabled = false;
}
else
{
flashlight.enabled = true;
}
}
}
}
If you are going to make your FlashLight a child of the Hand you would need to remove these two lines from your code
transform.localRotation = someBone.localRotation;
transform.localScale = someBone.localScale;
Since that will rotate and scale the FlashLight as well as the hand.

Categories