I am working with the XR Interaction Toolkit and using the Oculus Plugin. I have a Swimming script using the controller velocity to swim through the "water" but right now, I can only get it to work in FixedUpdate by itself. I want it to only be called when my player enters the water. I have tried to call it in OnCollionEnter/Stay but doesn't seem to work.
Can I call an If statement for a collision in FixedUpdate? I cannot figure out how to do that.
Here is my code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(Rigidbody))]
public class Swimmer : MonoBehaviour
{
[Header("Values")]
[SerializeField] float swimForce = 2f;
[SerializeField] float dragForce = 1f;
[SerializeField] float minForce;
[SerializeField] float minTimeBetweenStrokes;
[Header("References")]
[SerializeField] InputActionReference leftControllerSwimReference;
[SerializeField] InputActionReference leftControllerVelocity;
[SerializeField] InputActionReference rightControllerSwimReference;
[SerializeField] InputActionReference rightControllerVelocity;
[SerializeField] Transform trackingReference;
Rigidbody _rigidbody;
float _cooldownTimer;
private void Awake()
{
_rigidbody = GetComponent();
_rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}
private void FixedUpdate()
{
_cooldownTimer += Time.fixedDeltaTime;
_rigidbody.useGravity = false;
//add velocity when both controllers pressed
if (_cooldownTimer > minTimeBetweenStrokes&& leftControllerSwimReference.action.IsPressed()&& rightControllerSwimReference.action.IsPressed())
{
var leftHandVelocity = leftControllerVelocity.action.ReadValue();
var rightHandVelocity = rightControllerVelocity.action.ReadValue();
Vector3 localVelocity = leftHandVelocity + rightHandVelocity;
localVelocity *= -1;
//swim forward
if (localVelocity.sqrMagnitude > minForce * minForce)
{
Vector3 worldVelocity = trackingReference.TransformDirection(localVelocity);
_rigidbody.AddForce(worldVelocity * swimForce, ForceMode.Acceleration);
_cooldownTimer = 0f;
}
}
//apply water drag force when player is moving
if (_rigidbody.velocity.sqrMagnitude > 0.01f)
{
_rigidbody.AddForce(-_rigidbody.velocity * dragForce, ForceMode.Acceleration);
}
}
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.tag == "Water")
{
Debug.Log("Collision Enter");
}
}
private void OnCollisionExit(Collision collision)
{
if (collision.gameObject.name == "Water")
{
_rigidbody.useGravity = true;
}
}
}
↧