How do I use Cos and Sin animation, and at the same time follow the target(Player)?
I'm not seeing how to do that. I'm a beginner in programming.
public class Spirit : MonoBehaviour
{
//target player
private bool isFollowing;
public float followSpeed;
public Transform followTarget;
//Sin & Con animation
[SerializeField] private float frequency;
[SerializeField] private float amplitude;
[SerializeField] private float _frequency;
[SerializeField] private float _amplitude;
private void FixedUpdate()
{
if (isFollowing)
{
//This is used to follow the player
transform.position = Vector3.Lerp(transform.position, followTarget.position, followSpeed * Time.deltaTime);
//This is the animation with Cos and Sin.
float x = Mathf.Cos(Time.time * _frequency) * _amplitude;
float y = Mathf.Sin(Time.time * frequency) * amplitude;
float z = transform.position.z;
transform.position = new Vector3(x, y, z);
}
}
}
Making a spirit ball follow the player and animating it using Cos and Sin using the frequency and amplitude of both X and Y coordinates.
Your code is actually very close but you are overwriting the transform.position later so your previous lerp is not working. Just include your cos and sin calculations while you are handling the lerp. Here is how you can modify your code to make it work.
//target player
private bool isFollowing = true; // for testing
[SerializeField] private float _followSpeed = 1f;
[SerializeField] private Transform _followTarget;
//Sin & Con animation
[SerializeField] private float _frequency = 1f;
[SerializeField] private float _amplitude = 1f;
private void Update()
{
if (!isFollowing) return;
// including cos to target position.x and sin to target position.y
Vector3 targetPosition = new Vector3(_followTarget.position.x + Mathf.Cos(Time.time * _frequency) * _amplitude,
_followTarget.position.y + Mathf.Sin(Time.time * _frequency) * _amplitude,
_followTarget.position.z);
//now put above calculation into lerp
transform.position = Vector3.Lerp(transform.position, targetPosition, _followSpeed * Time.deltaTime);
}
Related
As you may know, the mode for the configurable spring has been removed, and I've discovered this following a Brackeys tutorial on multiplayer fps (part 5). There was a comment under the video saying that you should ignore this as Brackeys sets it manually in the code later. However, when I did this, there was no errors, but the jump button did nothing (yes I checked the inputs)
My code is below:
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
[RequireComponent(typeof(ConfigurableJoint))]
public class PlayerController : MonoBehaviour
{
private Vector3 _movHorizontal;
private Vector3 _movVertical;
private Vector3 _velocity;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float lookSensitivity = 5f;
[SerializeField]
private float thrusterForce = 1000f;
[Header("Spring Settings:")]
[SerializeField]
private JointDriveMode jointMode = JointDriveMode.Position;
[SerializeField]
private float jointSpring = 20f;
[SerializeField]
private float joinMaxForce = 40f;
private PlayerMotor motor;
private ConfigurableJoint joint;
void Start ()
{
motor = GetComponent<PlayerMotor>();
joint = GetComponent<ConfigurableJoint>();
SetJointSettings(jointSpring);
}
void Update ()
{
//Calc movement velocity as Vector 3D
float _xMov = Input.GetAxisRaw("Horizontal");
float _zMov = Input.GetAxisRaw("Vertical");
_movHorizontal = transform.right * _xMov;
_movVertical = transform.forward * _zMov;
//Final movement vector
_velocity = (_movHorizontal + _movVertical).normalized * speed;
//Apply movement
motor.Move(_velocity);
//Calculate rotation as a 3d vector (turning around)
float _yrot = Input.GetAxisRaw("Mouse X");
Vector3 _rotation = new Vector3 (0f, _yrot, 0f) * lookSensitivity;
//Apply rotation
motor.Rotate(_rotation);
//Calculate rotation as a 3d vector (turning around)
float _xrot = Input.GetAxisRaw("Mouse Y");
Vector3 _cameraRotation = new Vector3 (_xrot, 0f, 0f) * lookSensitivity;
//Apply rotation
motor.RotateCamera(_cameraRotation);
//Calculate thruster force based on player input
Vector3 _thrusterForce = new Vector3 (0, 0, 0);
if (Input.GetButton("Jump"))
{
_thrusterForce = Vector3.up * thrusterForce;
SetJointSettings(0f);
} else
{
SetJointSettings(jointSpring);
}
//Apply thruster force
motor.ApplyThruster(_thrusterForce);
}
private void SetJointSettings(float _jointSpring)
{
joint.yDrive = new JointDrive
{
mode = jointMode,
positionSpring = _jointSpring,
maximumForce = joinMaxForce
};
}
}
hello. I'm making a mobile joystick game where I should fly a plane. So I wrote a script that works but the plane does not turn as I wanted. for example I want to turn completely to the right to do 90 degrees but the plane continues straight by moving a little to the rightyour text
here is the script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlaneController : MonoBehaviour
{
public Joystick joystick;
public float forwardSpeed = 15f;
public float horizontalSpeed = 4f;
public float verticalSpeed = 4f;
public float smoothness = 5f;
public float maxHorizontalRotation=0.1f;
public float maxVerticalRotation = 0.06f;
public float rotationSmoothness=5f;
public Rigidbody rb;
private float horizontalInput;
private float verticalInput;
public float forwardSpeedMultiplier= 100f;
private float speedMultiplier=1000f;
// Start is called before the first frame update
void Start()
{
rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButton(0) || Input.touches.Length !=0) {//celui la pour jouer avec le téléphone
horizontalInput = joystick.Horizontal;
verticalInput= joystick.Vertical;
}
else // pour le pc
{
horizontalInput=Input.GetAxisRaw("Horizontal");
verticalInput=Input.GetAxisRaw("Vertical");
}
HandlePlaneRotation();
}
private void FixedUpdate(){
HandlePlaneMovement();
}
private void HandlePlaneMovement(){
rb.velocity=new Vector3(
rb.velocity.x,
rb.velocity.y,
forwardSpeed * forwardSpeedMultiplier * Time.deltaTime);
float xVelocity= horizontalInput * speedMultiplier * horizontalSpeed*Time.deltaTime;
float yVelocity= -verticalInput * speedMultiplier * verticalSpeed*Time.deltaTime;
rb.velocity= Vector3.Lerp(
rb.velocity,
new Vector3(xVelocity,yVelocity, rb.velocity.z),
Time.deltaTime * smoothness);
}
private void HandlePlaneRotation(){
float horizontalRotation = horizontalInput * maxHorizontalRotation;
float verticalRotation = verticalInput *maxVerticalRotation ;
transform.rotation = Quaternion.Lerp(
transform.rotation,
new Quaternion
(verticalRotation,
transform.rotation.y,
horizontalRotation,
transform.rotation.w),Time.deltaTime*rotationSmoothness
);
}
}
*Thank you*
I want you to tell me what I should do to fix this problem.
I already tried several things but I couldn't.
Thank.
Well, as I see in your code you are having a bit problem with how plane movement works.
first planes always have forward velocity so you don't need a joystick for handling that :
rb.AddForce(transform.forward * speed, ForceMode.Impulse);
But you can use the JoyStick joyStick for changing the forward vector of your plane (changing y Euler angle) and here is an example of doing that :
x = joyStick.Horizontal;
y = joyStick.Vertical;
yRot = Quaternion.LookRotation(Vector3.forward * y + Vector3.right * x, Vector3.up).eulerAngles.y;
It's a similar code as Assets/Joystick Pack/Examples/JoystickPlayer.cs but here we convert that force to a forward vector and use that for setting the Euler angle of an object.
Note: You can add some extra movement waves or noises to add more feeling to your plane movement.
Hope it was helpful.
Sorry, I'm a beginner in Unity but I want to move a gameobject on the Y-axis only and have it move with random speed so that sometimes it moves fast and sometimes slower.
this is my code. (it jitters because i figured out my mistake is I put the random speed on the update but I don't know how to fix it)
public class RandomUpDown : MonoBehaviour
{
[SerializeField] float minSpeed = 1f;
[SerializeField] float maxSpeed = 2f;
[SerializeField] float height = 4f;
Vector3 pos;
private void Start()
{
pos = transform.position;
}
void Update()
{
float randomSpeed = Random.Range(minSpeed, maxSpeed);
float newY = Mathf.Sin(Time.time * randomSpeed) * height + pos.y;
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
}
}
it really depends on what you want, but you can do this with a coroutine and a loop.
for example:
void Start()
{
StartCoroutine(myRandLoop)
}
public IEnumerator myRandLoop()
{
while(true)
{
float randomSpeed = Random.Range(minSpeed, maxSpeed);
float newY = Mathf.Sin(Time.time * randomSpeed) * height + pos.y;
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
yield return new WaitForSeconds(delayAmount)
}
}
I'm currently working on a fps game in which you can travel to asteroids and walk on them, currently I have gravity for those asteroids and I have a fps controller that works for all my other movement systems (swimming, floating) but translating it to the gravity of the asteroid is giving me a lot of trouble. I can get the controller to work perfectly on flat surfaces using Unity's gravity but not on the asteroid.
The current fps controller moves in the direction of the camera which means the character floats up when looking up, all my other fps controllers didn't work at all with the planet and this one is the closet I've gotten to getting it to work.
Is there anyway to fix this? I'm quite new to coding so any explanations would help me heaps!
Here's the code I'm using for the controller:
public Transform targetCamera;
public Rigidbody targetRigidbody;
public Transform targetBody;
public float walkSpeed = 9f;
public float runSpeed = 14f;
public float maxSpeed = 20f;
public float jumpPower = 30f;
public float extraGravity = 0;
float bodyRotationX;
float camRotationY;
Vector3 directionIntentX;
Vector3 directionIntentY;
float speed;
public bool grounded;
public float thrust = 20f;
public float forwardSwimSpeed = 45f;
private float xRotation;
private const float Sensitivity = 50f;
private const float SensitivityMultiplier = 1f;
private float desiredX;
public float dragMult = 2f;
public float rotationSmoothSpeed = 10f;
void Update()
{
Look();
targetRigidbody.drag = dragMult;
}
private void FixedUpdate()
{
if (targetRigidbody.velocity.magnitude > maxSpeed)
{
targetRigidbody.velocity = targetRigidbody.velocity.normalized * maxSpeed;
}
if (Input.GetKey(KeyCode.W))
AddForce(Vector3.forward);
if (Input.GetKey(KeyCode.S))
AddForce(Vector3.back);
if (Input.GetKey(KeyCode.A))
AddForce(Vector3.left);
if (Input.GetKey(KeyCode.D))
AddForce(Vector3.right);
if (Input.GetKey(KeyCode.Space))
AddForce(Vector3.up);
if (Input.GetKey(KeyCode.LeftControl))
AddForce(Vector3.down);
}
private void AddForce(Vector3 direction)
{
float scaledForwardSwimSpeed = Time.deltaTime * forwardSwimSpeed;
targetRigidbody.AddForce(targetCamera.transform.TransformDirection(
direction * thrust) * scaledForwardSwimSpeed,
ForceMode.Acceleration);
}
private void Look()
{
float mouseX = Input.GetAxis("Mouse X") * Sensitivity * Time.fixedDeltaTime * SensitivityMultiplier;
float mouseY = Input.GetAxis("Mouse Y") * Sensitivity * Time.fixedDeltaTime * SensitivityMultiplier;
Vector3 rotation = targetCamera.transform.localRotation.eulerAngles;
desiredX = rotation.y + mouseX;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
targetCamera.transform.localRotation = Quaternion.Euler(xRotation, desiredX, 0);
}
And here's the first of two bits of code for the asteroid: GravityCtrl
public float gravity = 10f;
private void OnTriggerEnter(Collider other)
{
if (other.GetComponent<GravityCtrl>())
{
other.GetComponent<GravityCtrl>().gravity = this.GetComponent<GravityOrbit>();
}
Here's the second: GravityOrbit
public GravityOrbit gravity;
private Rigidbody rb;
public float rotationSpeed = 20f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
if (gravity)
{
Vector3 gravityUp = Vector3.zero;
gravityUp = (transform.position - gravity.transform.position).normalized;
Vector3 localUp = transform.up;
Quaternion targetrotation = Quaternion.FromToRotation(localUp, gravityUp) * transform.rotation;
transform.up = Vector3.Slerp(transform.up, gravityUp, rotationSpeed * Time.deltaTime);
rb.AddForce((-gravityUp * gravity.gravity) * rb.mass);
}
I even set up public variables to see if was getting any input, and it isn't. I even copied and pasted the names directly from the project settings page.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class vehicle : MonoBehaviour
{
private Vector3 thrusterInput;
public float rotationSpeed = 10f;
public float rotSmoothSpeed = 10f;
private Quaternion smoothedRot = Quaternion.identity;
private Quaternion targetRot;
Body[] bodies;
public Rigidbody rigidbody;
public float thrustStrength = 10f;
// Start is called before the first frame update
void Start()
{
bodies = FindObjectsOfType<Body>();
}
// Update is called once per frame
void Update()
{
foreach(Body body in bodies)
{
float sqrDst = (body.transform.position - transform.position).sqrMagnitude;
Vector3 forceDir = (body.transform.position - transform.position).normalized;
Vector3 acceleration = forceDir * Universe.gravitationalConstant * body.rigid.mass / sqrDst;
rigidbody.AddForce(acceleration, ForceMode.Acceleration);
}
Vector3 thrustDir = transform.TransformVector(thrusterInput);
rigidbody.AddForce(thrustDir * thrustStrength, ForceMode.Acceleration);
rigidbody.MoveRotation(smoothedRot);
}
void HandleMovement()
{
float thrustInputX = Input.GetAxis("Horizontal");
float thrustInputY = Input.GetAxis("Ascent");
float thrustInputZ = Input.GetAxis("Vertical");
thrusterInput = new Vector3(thrustInputX, thrustInputY, thrustInputZ);
float yawInput = Input.GetAxis("Mouse X") * rotationSpeed;
float pitchInput = Input.GetAxis("Mouse Y") * rotationSpeed;
float rollInput = Input.GetAxis("Roll") * rotationSpeed;
Quaternion yaw = Quaternion.AngleAxis(yawInput, transform.up);
Quaternion pitch = Quaternion.AngleAxis(pitchInput, transform.right);
Quaternion roll = Quaternion.AngleAxis(rollInput, transform.forward);
targetRot = yaw * pitch * roll * targetRot;
smoothedRot = Quaternion.Slerp(transform.rotation, targetRot, Time.deltaTime * rotSmoothSpeed);
}
}
Sorry if the indents are all messed up, stackoverflow wasn't letting me use tab for some reason.
Your HandleMovement() is not called from anywhere. You need to put it in Update()