Problem with mathf function

Hi to all,
In this part of script, if you press D, the object should go up, instead it moves up and down at the same time… why? Can someone explain me this? Thank you

void Update () {

if (Input.GetKey (KeyCode.D)) {
           arm_rot = (Mathf.Sin (arm_sin) * 30.0f) - 30.0f;
           arm_sin = (arm_sin + Time.deltaTime * 5.0f) % 360.0f;
           arm[0].transform.localEulerAngles = new Vector3 (arm_rot, 0.0f, 0.0f );

There are a few things that don’t look quite right with your math there… First, you’re trying to take a sine from an angle in degrees, while usually trig methods work with Radians.

arm_sin % 360 won’t have the expected result here, as it will be treated as a value that is expected to range from 0 to 2PI. 360 in radians is quite a few turns, hehe.

This means you’re taking a sine value from a float that, as far as radians go, will just continue to increment. This is commonly used to produce a back-and-forth movement, as sin(t * f + p) * a is generally known as the sinewave equation, where t is a running time value, f is frequency, p is the phase shift, and a is amplitude.

Your code more closely resembles a sinewave than something meant to increment and decrement an angle. The fact that you’re using degrees where radians are expected could also mean you’re seeing very fast movement as well, which will look like jitter.

It’s hard to be of much more help without knowing exactly what you want to achieve here… Is the sin function being used because you want the arms to gradually ease to a stop at the extremes? Or do you just want linear motion for that X angle rotation? If the latter case is good enough, you could probably just remove the sine function altogether, and just increment/decrement an arm_angle float which is fed straight into the transform euler angles thing (that one uses degrees in fact, not radians).


I got this so far :

using UnityEngine;
using System.Collections;
public class Braccio : MonoBehaviour {
	public GameObject[] arm;

	float speed;

	void Awake()
		speed = 10f;

	// Update is called once per frame
	void Update () {
		// go down
		if (Input.GetKey (KeyCode.Z)) {

		   arm[0].transform.Rotate(Vector3.right * Time.deltaTime*speed);
		// go up
		if (Input.GetKey (KeyCode.X)) {

			arm[0].transform.Rotate(-Vector3.right * Time.deltaTime*speed);

Now you have to set your own limits for the movement (the range angle).
Which is another tricky problem by the way :stuck_out_tongue: