Search Unity

Trying to set object starting position and set range of movement

Discussion in 'Scripting' started by kentg1, Jan 18, 2019.

  1. kentg1

    kentg1

    Joined:
    Dec 22, 2014
    Posts:
    168
    I am trying to find the starting position of my space ship and set the range of y movement

    But I am getting series of errors when i do when saving the initial position - see attached

    Thank you

    Code (CSharp):
    1.  
    2. //speed of the enemy
    3. public float speed = 3f;
    4.  
    5. //range of movement Y
    6. public float rangeY = 2;
    7.  
    8. //initial position
    9. Vector3 initialPos;
    10.  
    11. //direction
    12. int direction = 1;
    13.  
    14. //save initial position
    15. initialPos = transform.position;
    16.  
    17. //how much are we moving?
    18. //Time.deltaTime, speed
    19. float movementY = speed * Time.deltaTime * direction;
    20.  
    21. //new position
    22. float newY = transform.posititon.y + movementY;
    23.  
    24. //checking whether we've left our range
    25. if(Mathf.Abs(newY - initialPos.y) > rangeY)
    26. {
    27.     direction *= -1;
    28. }
    29. //if we can move further, let's move further
    30. else
    31. {
    32.     transform.position += new Vector3(0, movementY, 0);
    33. }
    34. }
    35. 1
    36. 2
    37. 3
    38. 4
    39. 5
    40. 6
    41. 7
    42. 8
    43. 9
    44. 10
    45. 11
    46. 12
    47. 13
    48. 14
    49. 15
    50. 16
    51. 17
    52. 18
    53. 19
    54. 20
    55. 21
    56. 22
    57. 23
    58. 24
    59. 25
    60. 26
    61. 27
    62. 28
    63. 29
    64. 30
    65. 31
    66. 32
    67. 33
    68. //speed of the enemy
    69. public float speed = 3f;
    70. //range of movement Y
    71. public float rangeY = 2;
    72. //initial position
    73. Vector3 initialPos;
    74. //direction
    75. int direction = 1;
    76. //save initial position
    77. initialPos = transform.position;
    78. //how much are we moving?
    79. //Time.deltaTime, speed
    80. float movementY = speed * Time.deltaTime * direction;
    81. //new position
    82. float newY = transform.posititon.y + movementY;
    83. //checking whether we've left our range
    84. if(Mathf.Abs(newY - initialPos.y) > rangeY)
    85. {
    86.     direction *= -1;
    87. }
    88. //if we can move further, let's move further
    89. else
    90. {
    91.     transform.position += new Vector3(0, movementY, 0);
    92. }
    93. }
    94.  
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Your code isn't inside any functions (or classes)?
     
  3. R0b_

    R0b_

    Joined:
    Jul 11, 2018
    Posts:
    25
    I think you should do acourse on C#. I recommand checking out the website SoloLearn.